Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲

Android SharedPreferences 用法整理

編輯:關於 Android 程式設計

SharedPreferences 是 Android 提供的輕量級鍵值對儲存機制,適合保存設定值、標記位這類小量資料,底層以 XML 檔形式存在 App 的私有目錄中。以下依序說明取得物件、寫入、讀取與跨進程存取。

一、取得 SharedPreferences 物件

SharedPreferences mSharedPreferences =
        context.getSharedPreferences(SP_NAME, Activity.MODE_PRIVATE);

第一個參數是檔案名稱,第二個是存取模式。MODE_PRIVATE 表示只有本 App 可讀寫,這也是絕大多數情況該用的設定。

二、寫入資料

SharedPreferences 本身不提供寫入方法,必須先取得 Editor:

SharedPreferences.Editor editor = mSharedPreferences.edit();

editor.putInt("intKey", 100);
editor.putFloat("floatKey", 1.5f);
editor.putString("stringKey", "value");
editor.putBoolean("boolKey", true);

// 記得要 commit 或 apply 才會真正落地
editor.commit();

commit() 是同步寫入並回傳 boolean;apply() 則是先在記憶體更新、稍後非同步寫檔,不阻塞主執行緒,在 API 9 之後建議優先採用。

三、讀取資料

int defValue = 0;
int value = mSharedPreferences.getInt("intKey", defValue);

每個 getXxx 方法都需要帶入一個預設值。當指定的 key 不存在時,就會回傳這個預設值,因此千萬別忘了給合理的中繼值。

四、跨進程讀取

早期版本可以透過 createPackageContext() 搭配世界可讀寫模式來存取其他 App 的 SharedPreferences:

Context context = null;
try {
    context = this.createPackageContext("com.other.app",
            Context.CONTEXT_IGNORE_SECURITY);
} catch (NameNotFoundException e) {
    e.printStackTrace();
}

SharedPreferences sp = context.getSharedPreferences("com.other.app",
        Context.MODE_WORLD_READABLE + Context.MODE_WORLD_WRITEABLE);

int version = sp.getInt("ota_version", -1);

SharedPreferences.Editor editor = sp.edit();
editor.putInt("ota_version", 0);
editor.commit();

int version1 = sp.getInt("ota_version", -1);

需要特別注意的是,MODE_WORLD_READABLE 與 MODE_WORLD_WRITEABLE 從 API 17 起已被標記為不建議使用,API 24 以上呼叫時甚至會直接拋出 SecurityException。基於安全考量,跨 App 分享資料的正確做法應該改用 ContentProvider。

小結

  • SharedPreferences 適合少量、結構簡單的資料,大量資料請用資料庫或檔案。
  • 寫入一律經過 Editor,且別忘了 commit / apply。
  • 讀取時務必給定預設值。
  • 跨進程共用資料請改用 ContentProvider,不要再依賴世界可讀寫模式。
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © Android教程網 All Rights Reserved