查看SharedPreferences文档,它说:
"注意:目前这个类不支持跨多个进程使用.这将在以后添加."
所以它本身似乎并不是线程安全的.但是,对commit()和apply()有什么样的保证?
例如:
synchronized(uniqueIdLock){
uniqueId = sharedPreferences.getInt("UNIQUE_INCREMENTING_ID", 0);
uniqueId++;
sharedPreferences.edit().putInt("UNIQUE_INCREMENTING_ID", uniqueId).commit();
}
Run Code Online (Sandbox Code Playgroud)
是否可以保证uniqueId在这种情况下始终是唯一的?
如果没有,是否有更好的方法来跟踪持续存在的应用程序的唯一ID?
编辑: 下面描述的问题是由于一个非常奇怪的设备问题不是由任何编码相关的问题引起的.
我有一个preferenceActivity,其中有很多checkBoxPreferences.checkBoxPreference假设保存默认的共享首选项文件,然后在我打开应用程序时再次调用以更新UI.
这不会像它想象的那样发生.如果我关闭应用程序并将其重新打开,我的值仍然像他们想象的那样,但如果我使用任务管理器来结束应用程序,或者如果我重新启动手机(当应用程序未运行时),则调用defaultValues再次.
所以,我在onResume()中创建了一个SharedPreference来测试它.
SharedPreferences pref = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
Run Code Online (Sandbox Code Playgroud)
然后我检查该共享首选项中是否有密钥.
pref.contains("myCheckBoxPreference");
Run Code Online (Sandbox Code Playgroud)
当我关闭并重新打开它时,它返回true.如果我与任务管理器关闭或关闭和打开电话,则返回false.
所以,我尝试手动设置SharedPreference
SharedPreferences.Editor editor = pref.edit();
editor.putBoolean("myCheckBoxPreference", myCheckBoxPreference.isChecked());
editor.commit();
Run Code Online (Sandbox Code Playgroud)
然后我在checkboxpreference值更改时调用了它.我也尝试在onStop和onPause中调用它.尽管如此,如果我关闭应用程序并将其重新打开,pref.contains将返回true,但如果我重新启动手机并重新打开,则返回false.
所以我尝试使用SharedPreferences文件.
在类声明中:
public static final String PREFS = "prefs";
Run Code Online (Sandbox Code Playgroud)
在onResume()中:
SharedPreferences pref = this.getSharedPreferences(PREFS, 0);
Run Code Online (Sandbox Code Playgroud)
同样的行为,如果我只是关闭应用程序并将其重新打开,pref.contains仍会返回true,但如果我关闭并重新打开手机,则返回false.
然后,我尝试myCheckBoxPreference的键值改变的东西,没有为CheckBoxPreference符合XML密钥,它仍然有同样的效果.
我从手机上卸下了应用程序,然后打开电源并重新打开,然后重新安装,它仍然具有相同的效果.
android taskmanager preference preferenceactivity sharedpreferences