下面的模式被吹捧为从我的android应用程序中的任何地方获取应用程序上下文的方法。但有时执行MyApp.getContext()
会返回null。我尝试通过从getContext()
中删除static
来更改模式,以便执行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;
}
}
https://stackoverflow.com/questions/21994612
复制相似问题