SharedPreferences 詳解(多進程,存取數組解決方案)


一、SharedPreferences基本概念
文件保存路徑:/data/data/<包名>/shared_prefs目錄下目錄下生成了一個SP.xml文件
SharedPreferences對象本身只能獲取數據而不支持存儲和修改,存儲修改是通過Editor對象實現。
 
實現SharedPreferences存儲的步驟如下:
  1. 根據Context獲取SharedPreferences對象

  2. 利用edit()方法獲取Editor對象。

  3. 通過Editor對象存儲key-value鍵值對數據。

  4. 通過apply()或者commit()方法提交數據。

二、SharedPreferences相關api
  • SharedPreferences.Editor api:完成數據寫入操作

  

 

  • SharedPreferences api :完成數據讀取操作

   

 
  說明:所以的getXXX()方法,都支持默認值,即如果沒有找到與當前key值對應的value,則返回我們自己設置的默認值。
 
  • commit()方法與apply()方法的比較

         相同點:
  1. 二者都是提交preference修改數據

  2. 二者都是原子過程。

        區別:
  1. apply沒有返回值而commit返回boolean表明修改是否提交成功

  2. apply是將修改數據原子提交到內存,而后異步真正提交到硬件磁盤;而commit是同步的提交到硬件磁盤,因此,在多個並發的提交commit的時候,他們會等待正在處理的commit保存到磁盤后在操作,從而降低了效率。而apply只是原子的提交到內容,后面有調用apply的函數的將會直接覆蓋前面的內存數據,這樣從一定程度上提高了很多效率。

  3. apply方法不會提示任何失敗的提示。

      綜合上述,由於在一個進程中,sharedPreference是單實例,一般不會出現並發沖突,如果對提交的結果不關心的話,建議使用apply,當然需要確保提交成功且有后續操作的話,還是需要用commit的。
 
 
  • 對api的理解

1. commit介紹:public abstract boolean commit ()
       修改你的preferences,從Editor到SharePreferences。它執行所請求的修改,替代SharedPreferences中的任何數據,當2個editor同時修改preferences ,最后一個commit成功。如果不關注返回值或在程序的main線程使用時,推薦使用apply().

2. apply介紹:public abstract void apply ()
        區別:commit將同步的將數據寫到preferences;apply立即更改內存中的SharedPreferences,但是開始異步提交到磁盤中。保存失敗你也不會得到任何提示信息,如果在這個sharedPreferences有另外一個editor執行一個定期的commit,此時一個apply依舊未完成。commit將被阻塞,直到所有異步操作完成,以及自己的commit。由於SharedPreferences在進程中是單實例的。在忽悠返回值的前提下,取代任何實例的commit或apply都是安全的。

               
三、對數據集合的支持——可以直接寫入一個 Set<String>類型的集合,但是默認只支持HashSet<String>類型,其他類型會被自動轉型
 
Set<String>是一個接口,一般使用子類來完成相關的功能。

       如果你希望傳入的Set是一個有序的(跟插入時的順序一樣),那么使用LinkedHashSet<String>類型,構造好一個LinkedHashSet<String>對象之后,調用 SharedPreferences.EditorputStringSet(String key, Set<String> values)寫入。  按照常規的思維,通過SharedPreferences的getStringSet(String key)方法讀取出來數據,然后強制轉為LinkedHashLinked<String>,可是出現異常了,系統提示不能將HashSet<String>轉為LinkedHashSet<String>類型。也就是說取出來的值已經不再是我們寫入的類型了。所以就只能使用HashSet<String>默認的排序類型,這只能滿足那些不關系順序的情況。

 

四、SharedPreferences一次存入多個有序數據解決方案 (String 類型為例)——使用字符串拼接(StringBuilder)的方式

public void testSharedPreferences(Context context) {
        // 寫數據操作
        final String regularExpression = "#";
        final String key = "key";
        final String[] strings = { "1111", "2222", "3333" };
        final String defaultValue = "5555";
        final String fileName = "filename";
        final StringBuilder stringBuilder = new StringBuilder();
        for (int i = 0; i < strings.length; i++) {
            stringBuilder.append(strings[i]);
            if (i != strings.length - 1) {
                stringBuilder.append(regularExpression);
            }
        }
        SharedPreferences preferencesWrite = context.getSharedPreferences(fileName, Context.MODE_WORLD_READABLE); SharedPreferences.Editor editor = preferencesWrite.edit(); editor.putString(key, stringBuilder.toString()); editor.apply(); // 讀數據操作
        SharedPreferences preferencesRead = context.getSharedPreferences(fileName, Context.MODE_WORLD_READABLE);
        final String resultStr = preferencesRead.getString(key, defaultValue); // 沒有對應的key則返回“5555” final String[] resultArray = resultStr.split(regularExpression);  // 解析數據,字符串分割 for (String str : resultArray) {
            System.out.println(str);
        }
}

 

五、SharedPreferences多進程支持(雖然支持,但是還是不靠譜的,大量同時讀寫操作也會存在問題)

public static int getMode() {
    // MODE_MULTI_PROCESS is always on in apps targeting Gingerbread
    // (Android 2.3) and below, and off by default in later versions
    return Build.VERSION.SDK_INT > 8 ? 4 : 0;
}
   
public void test() {
    SharedPreferences settings = context.getSharedPreferences("fileName", getMode());
}

 

下面是getSharedPreferences方法的定義和解釋:

public abstract SharedPreferences getSharedPreferences (String name, int mode)

Added in  API level 1

Retrieve and hold the contents of the preferences file 'name', returning a SharedPreferences through which you can retrieve and modify its values. Only one instance of the SharedPreferences object is returned to any callers for the same name, meaning they will see each other's edits as soon as they are made.


免責聲明!

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



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