以下架构被吹捧为从我的Android应用程序中的任何位置获取应用程序上下文的方式.但有时候MyApp.getContext()返回null.我尝试通过删除static来改变模式,getContext()以便我这样做MyApp.getInstance().getContext().它仍然返回null.我该如何解决?如何从我的应用程序中的任何位置获取应用程序的上下文?
public class MyApp extends Application {
private static MyApp instance;
public static MyApp getInstance() {
return instance;
}
public static Context getContext() {
return instance.getApplicationContext();
}
@Override
public void onCreate() {
super.onCreate();
instance = this;
}
}
Run Code Online (Sandbox Code Playgroud)