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. }  
  • 相关阅读:
    CF225E Unsolvable
    CF1100E Andrew and Taxi
    oracle数据库导入导出方法
    ORACLE无法删除当前连接用户
     为什么上传文件的表单里要加个属性enctype----摘录
    ecplise 使用快捷键
    spring工作机制及为什么要用?
    阐述struts2的执行流程。
    Hibernate工作原理及为什么要用?
    Mybatis 如何自动生成bean dao xml 配置文件 generatorconfig.xml (main()方法自动生成更快捷)
  • 原文地址:https://www.cnblogs.com/exmyth/p/4779790.html
Copyright © 2011-2022 走看看