安卓:这是一个很好的做法,以获取上下文静态? [英] Android: It is a good practice to get Context statically?
问题描述
目前,在我的应用我有下面的类:
公共类MyApp的扩展应用{
私有静态上下文的背景下;
公共无效的onCreate(){
super.onCreate();
MyApp.context = getApplicationContext();
}
公共静态上下文的getContext(){
返回MyApp.context;
}
}
我用这个有背景信息类,既不活动,也不片段。它的使用有任何区别储存在这个类和使用,活性上下文语境?这是一个很好的做法,这个类,或者我应该提供一个活动的背景下,以谁需要它的任何类?
感谢。
这是有上下文存储在这个类和使用,活性方面?
使用有什么区别
是的。请阅读戴维·史密斯的史诗博客文章关于这个问题的。总结:只能使用应用程序
时,你知道的为什么 应用程序
是正确的答案。 ..它很少是。
这是一个很好的做法,这个类
恕我直言,不是一般。有时您可能需要一个应用程序
的对象,但你并不需要自己的自定义子类,而你并不需要,使之成为单身。
我应该提供一个活动的背景下,以谁需要它的任何类?
您提供的右键的上下文
实例给任何需要它的方法。正如戴维·史密斯介绍了博客文章,不是所有的上下文
情况下都是一样的。仅使用应用程序
在 应用程序
是正确的排序背景
currently, in my App I have the following class:
public class MyApp extends Application {
private static Context context;
public void onCreate(){
super.onCreate();
MyApp.context = getApplicationContext();
}
public static Context getContext() {
return MyApp.context;
}
}
I use this to have Context in classes that are neither Activities nor Fragment. It's there any difference between use the context stored on this class and use and activity as context? It is a good practice to have this class or should I provide an activity as context to any class who needs it?
Thanks.
It's there any difference between use the context stored on this class and use and activity as context?
Yes. Please read Dave Smith's epic blog post on the subject. In summary: only use an Application
when you know why Application
is the right answer... and it rarely is.
It is a good practice to have this class
IMHO, not usually. You may sometimes need an Application
object, but you do not need your own custom subclass, and you do not need to make it a singleton.
should I provide an activity as context to any class who needs it?
You supply the right Context
instance to any method that needs it. As Dave Smith describes in that blog post, not all Context
instances are created equal. Only use Application
when Application
is the right sort of Context
.
这篇关于安卓:这是一个很好的做法,以获取上下文静态?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!