这里我创建了一个 SharedPreferences
如果我没记错的话我正在使用这个代码:
SharedPreferences sp = getPreferences(Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sp.edit();
editor.putLong("ExactTime", minutesToMilliseconds(NumberPicker2.getValue()));
editor.commit();
我正在做的是从 NumberPicker
获得一个 value
并且我想保存这个 value
并且一旦用户重新启动APP 甚至重启设备(我不知道 SharedPreferences
是否这样做...)当用户打开 APP 时,它仍然是从 NumberPicker
中选择的号码。
我想在扩展 Service
的类中使用它。我试过的是:
SharedPreferences sp = this.getSharedPreferences("ExactTime", Context.MODE_PRIVATE);
WifiTimeSearch = sp.getLong("ExactTime", 0);
这是我迷路的地方......我读到这个“0”表示默认值,但我想使用我存储在 SharedPreferences
上的相同值。 . 而当我尝试使用此 Long
值时,该值为“0”。
我做错了什么?
最佳答案
您正在读取和写入不同的 SharedPreference 文件。
此外,通过使用 getPreferences()
,您正在写入该 Activity 的本地 SharedPreferences。
来自源代码:
/**
* Retrieve a {@link SharedPreferences} object for accessing preferences
* that are private to this activity. This simply calls the underlying
* {@link #getSharedPreferences(String, int)} method by passing in this activity's
* class name as the preferences name.
*
* @param mode Operating mode. Use {@link #MODE_PRIVATE} for the default
* operation, {@link #MODE_WORLD_READABLE} and
* {@link #MODE_WORLD_WRITEABLE} to control permissions.
*
* @return Returns the single SharedPreferences instance that can be used
* to retrieve and modify the preference values.
*/
public SharedPreferences getPreferences(int mode) {
return getSharedPreferences(getLocalClassName(), mode);
}
要使其正常工作,只需为您的应用使用默认的 SharedPreferences:
写作:
SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(this);
SharedPreferences.Editor editor = sp.edit();
editor.putLong("ExactTime", minutesToMilliseconds(NumberPicker2.getValue()));
editor.commit();
阅读:
SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(this);
WifiTimeSearch = sp.getLong("ExactTime", 0);
请注意,只要您在 Activity 或 Service 中,就可以使用 this
作为 Context。
关于android - SharedPreferences 长值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31123798/