Using Application context everywhere?

后端 未结 9 1006
难免孤独
难免孤独 2020-11-22 01:52

In an Android app, is there anything wrong with the following approach:

public class MyApp extends android.app.Application {

    private static MyApp instan         


        
9条回答
  •  萌比男神i
    2020-11-22 01:59

    Application Class:

    import android.app.Application;
    import android.content.Context;
    
    public class MyApplication extends Application {
    
        private static Context mContext;
    
        public void onCreate() {
            super.onCreate();
            mContext = getApplicationContext();
        }
    
        public static Context getAppContext() {
            return mContext;
        }
    
    }
    

    Declare the Application in the AndroidManifest:

    
    

    Usage:

    MyApplication.getAppContext()
    

提交回复
热议问题