android - 从 SharedPreferences.Editor 调用 apply() 后立即恢复首选项是否安全?

标签 android concurrency sharedpreferences

我在决定是否应该使用来自 SharedPreferences.Editorapply()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/

相关文章:

java - 将自定义数组列表存储在 SharedPreferences 中并从那里获取它?

flutter - 如何在Flutter中使用SharedPreferences保存List <List <String >>

android - 云到设备消息传递 (C2DM) 如何工作?

android - 从应用程序商店获取 cordova 应用程序版本的插件?

android - Intent 自定义权限不起作用

java - 调用接口(interface)时使用匿名类

java - ExecutorService 和 Lambdas - .execute(() -> ...) 和 .execute() 之间的区别

arrays - 尝试仅将唯一元素添加到数组中

java - 具有特殊用例的 JAVA 中的一项 (int) 缓存

android - 共享首选项 - CastException : HashSet cannot be cast to TreeSet