preferenceManager.getDefaultShared preferences()VS GET preferences()getDefaultShared、preferenceManag

2023-09-04 10:43:21 作者:一生热爱难回头

PreferenceManager.getDefaultSharedPreferences(context)

getPreferences()

似乎检索不同的preferences。

seem to retrieve different Preferences.

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

我返回false,

for me returns false,

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

返回true。

returns true.

在preference写与像

The Preference was written with an Editor like

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

我如何从场景中获得的活动之外同preferences?

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

推荐答案

从Android的GitHub库( 1 ),我们可以看到,获取preferences 不做任何事除了调用 getShared preferences 方法与当前的类名。

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 );
}

没有什么访问共享preference适当的类名称限制其他活动/ code。更重要的是,我preFER的不可以使用获取preferences ,因为这意味着=>永远不会改变的活动名称。如果您更改,然后采取访问共享preferences照顾具有明确提到早前类名(升级前)。

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 ).