Tips for global access to Context
In Android Development, there are many places where context contexts are used , such as: Popup Toast
When necessary, when you need to launch the event, when you need to send the broadcast, when you need to operate the database, use the
When you know it, you need to wait.
Assuming that it is in Activity , it is very easy to get the context object because the activity itself inherits Context. The direct benefit of this is possible.
But for the more complex logic, the code is not in the Activity . So. Getting the Context is not so easy.
Here's a tip to tell you:
Android provides a application class. Each time the application starts, the system will voluntarily
To initialize.
And we can customize a application class to make it easier to manage some of the global state information in the program, such as the global context.
1, create a new class MyApplication inherit application.
The code is as follows:
Package Com.example.networktest;public class MyApplication extends application { private static context context; @Override public void OnCreate () { context = Getapplicationcontext (); } public static Context GetContext () { return context; }}
2, under the <application> tag of the androidmanifest.xml file to be able to specify, The code looks like the following:
<manifest xmlns:android= "http://schemas.android.com/apk/res/android" package= "Com.example.networktest" Android : versioncode= "1" android:versionname= "1.0" >......<applicationandroid:name= " Com.example.networktest.MyApplication "... >......</application></manifest>
Note: Be sure to add the full package name when specifying MyApplication, or the system will not be able to find this
A class.
This way we have achieved a global access to the Context of the mechanism, and then whatever you want in the project, no matter where
Using Context, you just need to call Myapplication.getcontext () .
Tips for global access to context