zoukankan      html  css  js  c++  java
  • 操作SharedPreferences的注意点

    如果使用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. }  
  • 相关阅读:
    Log4Net使用指南
    构建Asp.Net2.0 GridView复合多层表头的几种方法
    javaScript中如何定义类
    是不是silverlight 2 的bug
    领悟 JavaScript 中的面向对象
    web拖动Drag&Drop原理
    一个不错的js验证框架
    MySQL中文参考手册
    高效实现数据仓库的七个步骤
    什么是ARP?如何防范ARP欺骗?
  • 原文地址:https://www.cnblogs.com/exmyth/p/4779790.html
Copyright © 2011-2022 走看看