Get application context returns null

后端 未结 6 911
隐瞒了意图╮
隐瞒了意图╮ 2020-11-27 18:49

The following schema has been touted as the way to get application context from anywhere within my android app. But sometimes doing MyApp.getContext() returns n

6条回答
  •  感情败类
    2020-11-27 19:27

    Create in onCreate() an instance of getApplicationContext() (mContext) then call MyApp.getContext() from everywhere in your app and you will get your application context statically.

    public class MyApp extends Application {
     //private static MyApp instance;
     private static Context mContext;
    
        public static MyApp getInstance() {
            return instance;
        }
    
        public static Context getContext() {
          //  return instance.getApplicationContext();
          return mContext;
        }
    
        @Override
        public void onCreate() {
            super.onCreate();
        //  instance = this;
         mContext = getApplicationContext();    
        }
    }
    

    Remember to declare into your AndroidManifest.xml

    
    ...
    ...
    ...
    
    

提交回复
热议问题