Android的 - 存储引用的ApplicationContext [英] Android - storing references to ApplicationContext

查看:122
本文介绍了Android的 - 存储引用的ApplicationContext的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个持有一些应用程序preferences之类的东西静态preferences类。它是确定存储引用的ApplicationContext呢?我需要一个参考,所以我可以得到的缓存文件夹之类的东西,在这不继承活动课。

I have a static Preferences class that hold some application preferences and stuff like that. Is it ok to store reference to ApplicationContext there? I need that reference so i can get cache folder and stuff like that in classes that don't inherit Activity.

推荐答案

您说得对使用的ApplicationContext 有,因为如果你不这样做的it可引起显著内存泄漏的。

You're right to use the ApplicationContext there since if you don't it can cause significant memory leaks.

不过,你有问题的是,静态变量可能不会保留它的价值。由于该机器人处理的应用程序有可能是您的应用程序可以被杀死,然后重新启动的方式 - 通常是由于用户切换到其他应用程序 - 这样的方式,你的静态变量将成为空和你的code这台将不会运行。 <一href="http://stackoverflow.com/questions/1944369/android-static-object-lifecycle-application-act-crazy">Have一看这个问题进行更详细的解答。

However, the problem you have is that the static variable may not retain its value. Due to the way that Android handles applications it is possible that your application could be killed and then restarted - usually due to the user switching to other applications - in such a way that your static variable will become null and your code which sets it won't be run. Have a look at this question for a more detailed answer.

这也许可以解决这个问题,但测试所有可能会导致您的变量落得准备将是耗时且容易出错。所以在我的静态preference类我已经做任何需要一个上下文的方法把它作为一个参数。例如:

It may be possible to work around this problem but testing all the possibilities that may cause your variable to end up null would be time-consuming and error prone. So in my static preference classes I have made any of the methods which require a Context take it as an argument. For example:

static int getSomeIntegerPreference(Context context) {
    return PreferenceManager.getDefaultSharedPreferences(context).getInt(PREFERENCE_SOME_INTEGER, 0);   
}

这是丑陋的,但它的工作原理。

It's ugly but it works.

这篇关于Android的 - 存储引用的ApplicationContext的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆