如果使用SharedPreferences用于資料存取,大部分人喜歡使用如下代碼:
- 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() {
- int pos = preferences.getInt("pos", 0);
- return pos;
但很多人忽略了一點,就是跨程序使用的時候,你就會發現從SharedPreferences讀出來的資料永遠都是第一次寫入的資料。 舉例,例如播放器是一個獨立程序,另外某個Activity是另一個獨立程序,播放器與這個Activity利用SharedPreferences通信的時候,如果使用MODE_PRIVATE操作模式,就會出錯。
是以,如果跨程序使用SharedPreferences的使用,需要使用MODE_MULTI_PROCESS模式,代碼如下:
- SharedPreferences preferences = getApplicationContext().getSharedPreferences("test", Context.MODE_MULTI_PROCESS);