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.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.

另请参阅参考-sharedpreferences-does-not-save-on-force-close.

相关文章

Android性能优化——之控件的优化 前面讲了图像的优化,接下...
前言 上一篇已经讲了如何实现textView中粗字体效果,里面主要...
最近项目重构,涉及到了数据库和文件下载,发现GreenDao这个...
WebView加载页面的两种方式 一、加载网络页面 加载网络页面,...
给APP全局设置字体主要分为两个方面来介绍 一、给原生界面设...
前言 最近UI大牛出了一版新的效果图,按照IOS的效果做的,页...