问题描述
我知道在Android上使用静态变量的风险很大,尤其是在您将其引用为活动的情况下.但是,如果我有一个扩展Application的类(我们称此类为"App"),那么引用该类的实例是否安全?
I know that usage of static variables on Android is quite risky, especially if you reference them to activities. However, if I have a class that extends Application (let's call this class "App"), is it safe to reference to the instance of this class?
如果是这样,任何其他类对应用程序上下文进行任何形式的引用也安全吗?我的意思是,如果我在任何类型的类中都引用了应用程序上下文,会不会发生内存泄漏?
If so, is it also safe for any other class to have any kind of reference to the application context? I mean, can there be a memory leak if I have a reference to the application context in any kind of class?
目的是,无论我在哪个范围内,都可以始终获得对应用程序上下文的引用.我认为这是安全的,因为如果系统关闭应用程序,则静态变量也将消失,直到下一次应用程序再次启动时为止,这将再次初始化静态变量.
The purpose is that no matter in which scope I am in, I can always get a reference to the application context. I think it's safe, since if the system closes the application, the static variable is also gone till the next time the application starts again, which will initialize the static variable again.
此外,这并不重要,但是如果我使用多个进程,那么在每个进程上我对App类的引用会完全不同吗?
Also, not that it matters much, but if I use multiple processes, will I get totally different references to App class on each process?
作为代码示例,这是我在考虑的问题:
As an example of code, here's what I'm thinking about:
public class App extends Application
{
private static Context _appContext;
@Override
public void onCreate()
{
super.onCreate();
_appContext = this;
}
public static Context getAppContext()
{
return _appContext;
}
}
推荐答案
目前,是的,它看起来很安全.尽管我不会getAppContext()
返回Context
,而是返回App
或Application
.
Presently, yes, it appears to be safe, though I would not have getAppContext()
return Context
, but instead return App
or Application
.
话虽如此,但实际上Android核心团队并未以这种方式进行设置,这表明也许存在一些我们尚未意识到的隐藏问题,或者将来这种方法可能会带来问题.
That being said, the fact that the core Android team did not set it up this way in the first place suggests that perhaps there may be hidden issues of which we are unaware, or that in the future this approach may introduce problems.
俗语的缩写是 YMMV . :-)
As the acronym of the saying goes, YMMV. :-)
编辑
我不知道您在这里所说的安全"是什么意思.
I have no idea what you mean by "safe" here.
如果您使用多个进程,则应该用鳟鱼打耳光.但是,是的,每个进程应该获得不同的App
实例.
If you use multiple processes, you should be slapped with a trout. But, yes, you should get distinct App
instances per process.
这篇关于在Android中将应用上下文保存到静态变量是否安全?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!