preferenceManager.getDefaultShared preferences()VS GET preferences() [英] PreferenceManager.getDefaultSharedPreferences() vs getPreferences()

查看:464
本文介绍了preferenceManager.getDefaultShared preferences()VS GET preferences()的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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库(<一href="https://github.com/android/platform_frameworks_base/blob/android-sdk-4.4.2_r1/core/java/android/app/Activity.java#L4517"相对=nofollow> 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 ).

这篇关于preferenceManager.getDefaultShared preferences()VS GET preferences()的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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