本文介绍了PreferenceManager.getDefaultSharedPreferences() 与 getPreferences()的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

PreferenceManager.getDefaultSharedPreferences(context)

getPreferences()

似乎检索不同的首选项.

seem to retrieve different Preferences.

PreferenceManager.getDefaultSharedPreferences(context).getBoolean(
                        "userWasAskedToEnableGps", false);

对我来说返回false,

for me returns false,

getPreferences(MODE_PRIVATE).getBoolean("userWasAskedToEnableGps", false);

返回真.

首选项是用像这样的编辑器编写的

The Preference was written with an Editor like

Editor e = getPreferences(MODE_PRIVATE).edit();
e.putBoolean (...);
e.commit();

如何在 Activity 之外从上下文中获得相同的首选项?

How can I get the same Preferences outside of an Activity from the Context?

推荐答案

来自 android github repo(1),我们可以看到 getPreferences 除了调用当前类的 getSharedPreferences 方法姓名.

From android github repo(1), we can see that getPreferences does nothing other than invoking getSharedPreferences method with current class name.

public SharedPreferences getPreferences( int mode ) {
    return getSharedPreferences( getLocalClassName(), mode );
}

没有任何限制其他活动/代码访问具有适当类名的共享首选项.更重要的是,我更喜欢使用getPreferences,因为这意味着=>永远不要更改活动名称.如果您更改,请注意访问共享首选项,并明确提及较早的类名(升级前).

There is nothing limiting other activities/code from accessing the shared preference with appropriate class name. More importantly, I prefer not to use getPreferences, since that implies => never ever change the Activity name. If you change, then take care of the accessing shared preferences with explicit mentions to the earlier class name ( before upgrade ).

这篇关于PreferenceManager.getDefaultSharedPreferences() 与 getPreferences()的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

06-25 05:16