What's the difference between commit() and apply() in SharedPreferences

后端 未结 8 2303
你的背包
你的背包 2020-11-22 10:03

I am using SharedPreferences in my android app. I am using both commit() and apply() method from shared preference. When I use AVD 2.3

8条回答
  •  鱼传尺愫
    2020-11-22 10:23

    The docs give a pretty good explanation of the difference between apply() and commit():

    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. As SharedPreferences instances are singletons within a process, it's safe to replace any instance of commit() with apply() if you were already ignoring the return value.

提交回复
热议问题