The easiest way to get the application context is:
Create a class App
that extends android.app.Application
public class App extends Application {
public static Context context;
@Override public void onCreate() {
super.onCreate();
context = getApplicationContext();
}
}
Modify your AndroidManifest.xml
's <application>
tag to have the attribute android:name="your.package.name.App"
.
Any time you need the application context, just get it from App.context
.
Application
is always initialized first whether your process runs, whether it's an activity, a service, or something else. You will always have access to the application context.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…