gpt4 book ai didi

java - Android SharedPreferences 中 commit 和 apply 的区别

转载 作者:IT老高 更新时间:2023-10-28 20:40:11 25 4
gpt4 key购买 nike

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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com