我有一个方法如下:
public static void addHighligtedDate(String date){
prefs = context.getSharedPreferences(Fields.SHARED_PREFS_FILE, 0);
Set<String> highlightedDates = prefs.getStringSet(Fields.HIGHLIGHTED_DATES, new HashSet<String>());
highlightedDates.add(date);
SharedPreferences.Editor editor = prefs.edit();
editor.putStringSet(Fields.HIGHLIGHTED_DATES, highlightedDates);
editor.commit();
}
现在的场景是这样的:
当我打开应用程序添加要突出显示的日期时,它们会突出显示,因为 SharedPreferences 包含这些值。当我按下主页按钮退出应用程序并返回时,这些值仍然存在。
但是,当从最近使用的应用程序中删除该应用程序时,这些值就会消失。这是正常行为还是我做错了什么?
查看文档:
This data will persist across user sessions (even if your application is killed).
最佳答案
SharedPreferences
始终随应用程序卸载一起删除。
当您卸载任何应用程序时,该应用程序在您的内存中所做的所有更改都将被撤销,这意味着您的 SharedPreference 文件、其他数据文件、数据库文件、应用程序 会被 Android 操作系统自动删除.
检查 - how-to-remove-shared-preference-while-application-uninstall-in-android .
更新:
但是,当应用程序被终止或关闭时,SharedPreferences
中的值仍然存在。您的代码中存在一些问题。
将方法改为-
public static void addHighligtedDate(String date){
prefs = context.getSharedPreferences(Fields.SHARED_PREFS_FILE, 0);
Set<String> highlightedDates = prefs.
getStringSet(Fields.HIGHLIGHTED_DATES, new HashSet<String>());
highlightedDates.add(date);
SharedPreferences.Editor editor = prefs.edit();
editor.clear();
editor.putStringSet(Fields.HIGHLIGHTED_DATES, highlightedDates);
editor.commit();
}
更新:
public abstract Set getStringSet (String key, Set defValues)
Retrieve a set of String values from the preferences.
Note that you must not modify the set instance returned by this call. The consistency of the stored data is not guaranteed if you do, nor is your ability to modify the instance at all.
Parameters
key The name of the preference to retrieve.
defValues Values to return if this preference does not exist.
关于android - SharedPreferences 值不会持续存在?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24650870/