public class MyApp extends Application {
private static Context context;
public void onCreate(){
super.onCreate();
MyApp.context = getApplicationContext();
}
public static Context getContext() {
return MyApp.context;
}
}
我使用它来在既不是活动也不是片段的类中使用Context.使用存储在此类上的上下文与使用和活动作为上下文之间有什么区别?有这个课程是一个好习惯,还是应该为任何需要它的班级提供一个活动作为背景?
谢谢.
解决方法:
It’s there any difference between use the context stored on this class and use and activity as context?
是.请阅读有关该主题的Dave Smith’s epic blog post.总结:当你知道为什么Application是正确的答案时,只使用一个应用程序……而且它很少.
It is a good practice to have this class
恕我直言,通常不是.有时您可能需要一个Application对象,但是您不需要自己的自定义子类,也不需要将它设为单例.
should I provide an activity as context to any class who needs it?
您可以为需要它的任何方法提供正确的Context实例.正如Dave Smith在该博客文章中描述的那样,并非所有Context实例都是平等的.仅当Application是正确的Context时才使用Application.
标签:android
来源: https://codeday.me/bug/20191007/1867530.html