博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
SharedPreferences的使用注意事项
阅读量:7232 次
发布时间:2019-06-29

本文共 1208 字,大约阅读时间需要 4 分钟。

hot3.png

如果使用SharedPreferences用于数据存取,大部分人喜欢使用如下代码:

public void writeSharedprefs(int pos) {   

    SharedPreferences preferences = getApplicationContext().getSharedPreferences("info", Context.MODE_PRIVATE); 
    SharedPreferences.Editor editor = preferences.edit(); 
    editor.putInt("t1", t1); 
    editor.commit();
 
public int writeSharedprefs() { 
    SharedPreferences preferences = getApplicationContext().getSharedPreferences("info", Context.MODE_PRIVATE); 
    int pos = preferences.getInt("t1", 0); 
    return pos; 

但很多人忽略了一点,就是跨进程使用的时候,你就会发现从SharedPreferences读出来的数据永远都是第一次写入的数据。 举例,例如播放器是一个独立进程,另外某个Activity是另一个独立进程,播放器与这个Activity利用SharedPreferences通信的时候,如果使用MODE_PRIVATE操作模式,就会出错。

所以,如果跨进程使用SharedPreferences的使用,需要使用MODE_MULTI_PROCESS模式,代码如下:

public void writeSharedprefs(int pos) { 
    SharedPreferences preferences = getApplicationContext().getSharedPreferences("info", Context.MODE_MULTI_PROCESS); 
    SharedPreferences.Editor editor = preferences.edit(); 
    editor.putInt("t1", t1); 
    editor.commit();  
 
public int writeSharedprefs() { 
    SharedPreferences preferences = getApplicationContext().getSharedPreferences("test", Context.MODE_MULTI_PROCESS); 
    int t1 = preferences.getInt("t1", 0); 
    return pos; 
}

转载于:https://my.oschina.net/u/1046838/blog/404444

你可能感兴趣的文章
020——VUE中变异方法push的留言版实例讲解
查看>>
Java并发编程:自己动手写一把可重入锁
查看>>
YOLO 详解
查看>>
Ember.js: Rich Web Applications Done Right
查看>>
活动图(Activity Diagram)—UML图(四)
查看>>
学JS必看-JavaScript数据结构深度剖析
查看>>
【NLP】蓦然回首:谈谈学习模型的评估系列文章(二)
查看>>
iOS开发之功能模块--长方形UIImage截取中间最大正方形区域
查看>>
04.SQLServer性能优化之---读写分离&数据同步
查看>>
Form 表单中的Input元素回车时不保存表单
查看>>
大神php摘录
查看>>
MySQL常用查询
查看>>
drop user 报错ora-00604
查看>>
微信JSSDK支付接口-安卓机无法正常调起接口
查看>>
XMPP使用简单介绍--登录
查看>>
Mac_IntelliJ IDEA For Mac 快捷键
查看>>
JavaCC从入门到出门
查看>>
iOS - 社会化分享-微信分享,朋友圈分享
查看>>
Xamarin XAML语言教程构建ControlTemplate控件模板
查看>>
第三章 消息摘要算法--MD5
查看>>