Getting the Application Context

后端 未结 6 1206
梦如初夏
梦如初夏 2020-12-02 23:16

This might be a simple question but I just wanted to make sure I am right.

In my android application I have a constructor that uses:

activity.getApp         


        
6条回答
  •  执念已碎
    2020-12-03 00:07

    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 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.

提交回复
热议问题