java - Android SharedPreferences 中 commit 和 apply 的区别

标签 java android sharedpreferences

SharedPreferences 用于在 Android 中保存应用程序数据。

commit()apply() 都用于保存共享首选项中的更改。

如 Android 库中所述:

public abstarct void apply():

Unlike commit(), which writes its preferences out to persistent storage synchronously, apply() commits its changes to the in-memory SharedPreferences immediately but starts an asynchronous commit to disk and you won't be notified of any failures. If another editor on this SharedPreferences does a regular commit() while a apply() is still outstanding, the commit() will block until all async commits are completed as well as the commit itself.

public abstract boolean commit ():

Commit your preferences changes back from this Editor to the SharedPreferences object it is editing. This atomically performs the requested modifications, replacing whatever is currently in the SharedPreferences.

这是否意味着 commit() 所做的更改与 apply() 相比是即时的?哪个更好?

如果我需要在下一个即时 Activity 中使用相同的共享偏好值,我应该使用哪一个?正如我所看到的,如果 Preference 的值被更新,它直到应用程序重新启动才会反射(reflect)出来。

最佳答案

Commit() 是即时的,但会执行磁盘写入。如果你在 ui 线程上,你应该调用 apply() 这是异步的。

关于java - Android SharedPreferences 中 commit 和 apply 的区别,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15335456/

相关文章:

java - 使用 jinstagram java 获取标签计数

android - 来自辅助类的sharedPreference

java(android) - 意外错误

java - 在整个数据库中搜索一个乱码 `�` - Oracle

android - 在服务中创建纹理 View 时从未调用 onSurfaceTextureAvailable

Android - 使用 "Set Wallpaper" Intent 设置墙纸

java - 杀死应用程序时 SharedPreferences 消失

android - 我可以使用 sharedPreferences 文件中的项目填充 AlertDialog 吗?

java - 使用 JAX-WS 在 java 中返回原始 SOAP 响应

android - 在 <select> 输入中显示图像而不是所选文本?