我在决定是否应该使用来自 SharedPreferences.Editor 的 apply()
或 commit()
时遇到问题
由于 apply()
是异步的,而且我们将在写入后立即读取,因此使用 commit()
更安全。另一方面,此方法可能会阻塞 UI 线程的时间过长。我不想使用局部变量,因为我想读取其他设置,并且由于我不知道 sendData()
将被调用,因此通过设置和局部变量读取的混合将添加不必要的复杂性。
// We need an Editor object to make preference changes.
// All objects are from android.context.Context
SharedPreferences settings = getSharedPreferences(PREFS_NAME, 0);
SharedPreferences.Editor editor = settings.edit();
editor.putBoolean("silentMode", mSilentMode);
// Apply the edits!
editor.apply();
// Read data of SharedPreferences (including other previously data)
// and send to web service
sendData();
上面是我想做的类似事情的代码 fragment 。我想确保当我从 SharedPreferences 读取任何数据时,所有设置都已提交。
最佳答案
既然你不知道 sendData()
什么时候会被调用那么你别无选择只能使用 commit
而不是 apply
当您读取并将其发送到外部服务器时,它会为您提供先前添加的数据,但如果它仍在将数据放入磁盘但您已经读取了数据,则不会应用,这会给您带来不一致的结果,因为它是异步执行的。
有一种方法可以知道数据已存储,通过在 SharedPreferences
中使用监听器 registerOnSharedPreferenceChangeListener
这只有在您始终知道最后添加到磁盘的数据时才有效在你阅读它之前。
关于android - 从 SharedPreferences.Editor 调用 apply() 后立即恢复首选项是否安全?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25433940/