在 PreferenceActivity 之外获取首选项

Getting preferences outside of PreferenceActivity

我得到了 PreferenceActivity。当用户更改首选项时,我想保存一些额外的首选项,所以在 OnPreferencesChange 方法中,我得到了这样的东西:

if(p.getKey().equals("mykey")) //there is no issue with this if. it enters and get inside to the commit command
{
   getPreferences(MODE_PRIVATE).edit().putString("otherKey","value").commit();
   return true;
}

我还得到了一个服务(当然 class 与 PreferenceActivity 的服务不同),我想在其中读取首选项。所以我正在做这样的事情:

sp = PreferenceManager.getDefaultSharedPreferences();
String val1 = dsp.getString("myKey","default1");
String val2 = dsp.getString("otherKey","default2");

我得到 "mykey" 的正确值,但 "otherKey" 总是得到 "default2"。这是为什么?会不会是Service获取错误的SharedPreference?

而不是

getPreferences(MODE_PRIVATE).edit().putString("otherKey","value").commit();

做:

PreferenceManager.getDefaultSharedPreferences( this ).edit().putString("otherKey","value").commit();

getPreferences() returns a "SharedPreferences object for accessing preferences that are private to this activity",根据文档。

正如文档所说 getPreferences:

Retrieve a SharedPreferences object for accessing preferences that are private to this activity. This simply calls the underlying getSharedPreferences(String, int) method by passing in this activity's class name as the preferences name.

getDefaultSharedPreferences:

Gets a SharedPreferences instance that points to the default file that is used by the preference framework in the given context.

所以这两个方法 return 不同的偏好对象,这就是为什么你得到默认值。

getPreferences(MODE_PRIVATE) 更改为 PreferenceManager.getDefaultSharedPreferences()