標籤:
如果使用SharedPreferences用於資料存取,大部分人喜歡使用如下代碼:
[java] view plaincopy
- public void writeSharedprefs(int pos) {
-
- SharedPreferences preferences = getApplicationContext().getSharedPreferences("test", Context.MODE_PRIVATE);
- SharedPreferences.Editor editor = preferences.edit();
- editor.putInt("pos", pos);
- editor.commit();
-
- }
-
- public int writeSharedprefs() {
- SharedPreferences preferences = getApplicationContext().getSharedPreferences("test", Context.MODE_PRIVATE);
- int pos = preferences.getInt("pos", 0);
- return pos;
- }
但很多人忽略了一點,就是跨進程使用的時候,你就會發現從SharedPreferences讀出來的資料永遠都是第一次寫入的資料。 舉例,例如播放器是一個獨立進程,另外某個Activity是另一個獨立進程,播放器與這個Activity利用SharedPreferences通訊的時候,如果使用MODE_PRIVATE操作模式,就會出錯。
所以,如果跨進程使用SharedPreferences的使用,需要使用MODE_MULTI_PROCESS模式,代碼如下:
[java] view plaincopy
- public void writeSharedprefs(int pos) {
-
- SharedPreferences preferences = getApplicationContext().getSharedPreferences("test", Context.MODE_MULTI_PROCESS);
- SharedPreferences.Editor editor = preferences.edit();
- editor.putInt("pos", pos);
- editor.commit();
-
- }
-
- public int writeSharedprefs() {
- SharedPreferences preferences = getApplicationContext().getSharedPreferences("test", Context.MODE_MULTI_PROCESS);
- int pos = preferences.getInt("pos", 0);
- return pos;
- }
操作SharedPreferences的注意點