码迷,mamicode.com
首页 > 其他好文 > 详细

操作SharedPreferences的注意点

时间:2015-09-03 01:47:10      阅读:140      评论:0      收藏:0      [点我收藏+]

标签:

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

 

[java] view plaincopy
 
  1. public void writeSharedprefs(int pos) {  
  2.   
  3.     SharedPreferences preferences = getApplicationContext().getSharedPreferences("test", Context.MODE_PRIVATE);  
  4.     SharedPreferences.Editor editor = preferences.edit();  
  5.     editor.putInt("pos", pos);  
  6.     editor.commit();  
  7.   
  8. }  
  9.   
  10. public int writeSharedprefs() {  
  11.     SharedPreferences preferences = getApplicationContext().getSharedPreferences("test", Context.MODE_PRIVATE);  
  12.     int pos = preferences.getInt("pos", 0);  
  13.     return pos;  
  14. }  


 

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

 

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

[java] view plaincopy
 
    1. public void writeSharedprefs(int pos) {  
    2.   
    3.     SharedPreferences preferences = getApplicationContext().getSharedPreferences("test", Context.MODE_MULTI_PROCESS);  
    4.     SharedPreferences.Editor editor = preferences.edit();  
    5.     editor.putInt("pos", pos);  
    6.     editor.commit();  
    7.   
    8. }  
    9.   
    10. public int writeSharedprefs() {  
    11.     SharedPreferences preferences = getApplicationContext().getSharedPreferences("test", Context.MODE_MULTI_PROCESS);  
    12.     int pos = preferences.getInt("pos", 0);  
    13.     return pos;  
    14. }  

操作SharedPreferences的注意点

标签:

原文地址:http://www.cnblogs.com/exmyth/p/4779790.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!