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.