使用哪个上下文?
我正在编写一个 Android 应用程序,我在 Context 方面遇到了一些问题。
我已阅读有关 Android 开发人员的避免内存泄漏文章。他们建议使用应用程序上下文而不是活动上下文来避免内存泄漏。
问题是,当我这样做时,我的应用程序在多个地方崩溃(使用 Nexus S,尽管我听说其他手机也会出现此问题)。
所以我有两个问题-
有人熟悉这个问题吗?
一般来说,我应该使用什么上下文?如果我的应用程序是使用活动上下文编写的,并且工作正常,我现在应该尝试重写它以使用应用程序上下文吗?
I'm writing an android app, and I have a little problem regarding Context.
I've read the Avoiding Memory Leaks article on Android developers. They suggest using application context instead of activity context to avoid memory leaks.
The problem is when I do that, my app crashes on several places(using Nexus S, although I heard this issue occurs is other phones as well).
So I have 2 questions-
Is anyone familiar with this issue?
In general, what context should I use? If my app is written using activity context, and it works fine, should I now try to rewrite it to use application context?
不要仅仅因为想要避免内存泄漏而使用该应用程序。除非您确实知道为什么使用它,否则不要使用它。正如本文所述,仅当您要创建与活动分开的对象时才使用它。根据定义,这些事情不应该做依赖于与活动相关的事情——显示对话框等。
Don't use the application just because you want to avoid memory leaks. Don't use it unless you actually know why you are using it. Only use it, as the article says, if you are creating objects that live separately from the activity. These things by definition should not be doing things that rely on the kinds of things associated with an activity -- showing dialogs, etc.