开发者

Android - storing references to ApplicationContext

I have a static Preferences class that hold some application pref开发者_JS百科erences 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.


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

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.

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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜