我在决定应该使用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();
上面是我想做的类似的代码片段。我想确保当我从SharedPreferences中读取任何数据时,所有设置都已提交。
最佳答案
由于您不知道何时会调用sendData()
,所以别无选择,只能使用commit
代替apply
,以便在读取并将其发送到外部服务器时会为您提供以前添加的数据,但是如果它仍将数据放入磁盘,但是您已经读取了数据,则将导致不一致的结果,即异步执行该数据,应用apply不会。
通过使用registerOnSharedPreferenceChangeListener
中的侦听器SharedPreferences
,有一种方法可以知道是否存储了数据,只有当您始终在读取磁盘之前始终知道最后添加到磁盘的数据时,此方法才有效。
关于android - 从SharedPreferences.Editor调用apply()之后立即恢复首选项是否安全?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/25433940/