到处使用应用程序上下文? [英] Using Application context everywhere?
问题描述
在 Android 应用中,以下方法是否有问题:
In an Android app, is there anything wrong with the following approach:
public class MyApp extends android.app.Application {
private static MyApp instance;
public MyApp() {
instance = this;
}
public static Context getContext() {
return instance;
}
}
并在需要上下文的任何地方(例如 SQLiteOpenHelper)传递它(当然不会泄漏)?
and pass it everywhere (e.g. SQLiteOpenHelper) where context is required (and not leaking of course)?
推荐答案
这种方法有几个潜在的问题,但在很多情况下(比如你的例子)它会很好地工作.
There are a couple of potential problems with this approach, though in a lot of circumstances (such as your example) it will work well.
特别是在处理任何需要 Context
的 GUI
时,你应该小心.例如,如果您将应用程序上下文传递到 LayoutInflater
中,您将得到一个异常.一般来说,您的方法非常好:在该 Activity
中使用 Activity's
Context
是一种很好的做法 和 Application Context
将超出 Activity
范围的上下文传递给
In particular you should be careful when dealing with anything that deals with the GUI
that requires a Context
. For example, if you pass the application Context into the LayoutInflater
you will get an Exception. Generally speaking, your approach is excellent: it's good practice to use an Activity's
Context
within that Activity
, and the Application Context
when passing a context beyond the scope of an Activity
to avoid memory leaks.
此外,作为您的模式的替代,您可以使用在 Context
上调用 getApplicationContext()
的快捷方式strong> 对象(例如 Activity)以获取应用程序上下文.
Also, as an alternative to your pattern you can use the shortcut of calling getApplicationContext()
on a Context
object (such as an Activity) to get the Application Context.
这篇关于到处使用应用程序上下文?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!