操作SharedPreferences的注意點


如果使用SharedPreferences用於數據存取,大部分人喜歡使用如下代碼:

 

[java]  view plain copy
 
  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 plain copy
 
    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. }  


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM