之间的提交和适用于Android的共享preferences差异 [英] Difference Between commit and apply in Android SharedPreferences

查看:145
本文介绍了之间的提交和适用于Android的共享preferences差异的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

共享preferences用来保存应用程序数据的机器人。

提交()适用()两者都使用将更改保存在共享preferences

正如Android的库:

 公共abstarct无效申请():
 

  

与提交(),其中写到了preferences出持久性   存储同步,适用()提交它的改变内存   共享$ P $立即pferences而是启动异步承诺   磁盘和任何故障,您将不会收到通知。如果其他编辑器   这种共享preferences并定期提交(),而适用()是   依然突出,提交()将阻塞,直到所有的异步提交的   完成并提交本身。

 公共抽象布尔提交():
 

  

这是这个编辑器来提交您的preferences变回   共享preferences对象是编辑。这种原子执行   要求修改,替换目前无论是在   共享preferences。

这是否意味着,由所做的更改提交()比较是​​即时的适用()?哪一个更好呢?

如果我需要使用相同的共享preference价值在未来的即时活动,哪一个我应该使用?正如我所看到如果preference值更新它不反映,直到重新启动应用程序。

解决方案

提交()是瞬时的,但执行磁盘写操作。如果你是在UI线程你应该调用适用(),这是异步的。

SharedPreferences are used to save Application data in Android.

commit() and apply() both are used to save the changes in the shared preferences.

As mentioned in Android Library:

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.

Does this mean that the changes made by commit() are instant as compared with apply()? Which one is better?

If I need to use the same shared preference value in the next immediate activity, which one should I use? As I have seen if the value of Preference is updated it is not reflected till the application is restarted.

解决方案

Commit() is instantaneous but performs disk writes. If you are on the ui thread you should call apply() which is asynchronous.

这篇关于之间的提交和适用于Android的共享preferences差异的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆