Tips for global access to Context
In Android Development, a context -sensitive object such as a popup Toast is used in many places:
When you need to start the activity, when you need to send the broadcast, when you need to operate the database, use the
When you know it, you need to wait.
If it is in Activity , it is easy to get the context object because the activity itself inherits Context, the direct benefit of this can be.
But for more complex logic, the code is not in the Activity , so getting the Context is not that easy.
Here's a tip to tell you:
Android provides a application class that automatically moves the class when the application starts
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, you can specify it under the <application> tab of the androidmanifest.xml file , as shown in the code below:
<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.
So that we have implemented a global access to the Context of the mechanism, after no matter you want to be anywhere in the project
Using Context, you just need to call Myapplication.getcontext () .
Tips for global access to context