Android O 8.0 SharedPreferences适配问题

Android O 8.0 SharedPreferences的适配问题

背景

在项目中遇到了Android O设备在恢复默认设置时用户的设置数据没有清空的情况,其他的系统版本都没有问题。

解决方案

项目中在SP的Editor clear之后调用的是apply()方法,经过测试修改为commit()就没有问题了。

对比SP Editor的apply和commit

太长不看想版本

commit()会将其首选项同步写入持久性存储
apply()会立即将其更改提交到内存
猜测Android O 同步时机发生了变化。

详细文档说明版

官方文档

public abstract void apply ()

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.
Note that when two editors are modifying preferences at the same time, the last one to call apply wins.
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.
You don’t need to worry about Android component lifecycles and their interaction with apply() writing to disk. The framework makes sure in-flight disk writes from apply() complete before switching states.

贴一个Google翻译

将您的首选项更改从此编辑器提交到正在编辑的SharedPreferences对象。这自动执行所请求的修改,替换SharedPreferences中当前的任何内容。
请注意,当两个编辑器同时修改首选项时,最后一个调用申请获胜。
与commit()不同,commit()会将其首选项同步写入持久性存储,apply()会立即将其更改提交到内存中的SharedPreferences,但会启动对磁盘的异步提交,并且不会通知任何失败。如果此SharedPreferences上的另一个编辑器在apply()仍未完成时执行常规commit(),则commit()将会阻塞,直到完成所有异步提交以及提交本身为止。
由于SharedPreferences实例是流程中的单例,因此如果您已经忽略了返回值,则可以使用apply()替换commit()的任何实例。
您不必担心Android组件生命周期及其与apply()写入磁盘的交互。该框架确保在切换状态之前,apply()完成正在进行的磁盘写入。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值