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

Android 工具類:SharedPrefsUtil 偏好設定封裝

編輯:關於 Android 程式設計

SharedPreferences 是 Android 中常用的輕量級資料儲存方式,適合保存設定、標記等簡單的鍵值資料。以下將其常見操作封裝成一個工具類,方便在專案各處統一呼叫。

/**
 * 偏好參數存儲工具類
 */
public class SharedPrefsUtil {

    /** 數據存儲的 XML 名稱 **/
    public final static String NAME = "QY";

    /** 存儲數據(Long) */
    public static void putLongValue(Context context, String key, long value) {
        context.getSharedPreferences(NAME, Context.MODE_PRIVATE)
               .edit().putLong(key, value).commit();
    }

    /** 存儲數據(Int) */
    public static void putIntValue(Context context, String key, int value) {
        context.getSharedPreferences(NAME, Context.MODE_PRIVATE)
               .edit().putInt(key, value).commit();
    }

    /** 存儲數據(String) */
    public static void putStringValue(Context context, String key, String value) {
        context.getSharedPreferences(NAME, Context.MODE_PRIVATE)
               .edit().putString(key, value).commit();
    }

    /** 存儲數據(boolean) */
    public static void putBooleanValue(Context context, String key, boolean value) {
        context.getSharedPreferences(NAME, Context.MODE_PRIVATE)
               .edit().putBoolean(key, value).commit();
    }

    /** 取出數據(Long) */
    public static long getLongValue(Context context, String key, long defValue) {
        return context.getSharedPreferences(NAME, Context.MODE_PRIVATE)
                      .getLong(key, defValue);
    }

    /** 取出數據(int) */
    public static int getIntValue(Context context, String key, int defValue) {
        return context.getSharedPreferences(NAME, Context.MODE_PRIVATE)
                      .getInt(key, defValue);
    }

    /** 取出數據(boolean) */
    public static boolean getBooleanValue(Context context, String key, boolean defValue) {
        return context.getSharedPreferences(NAME, Context.MODE_PRIVATE)
                      .getBoolean(key, defValue);
    }

    /** 取出數據(String) */
    public static String getStringValue(Context context, String key, String defValue) {
        return context.getSharedPreferences(NAME, Context.MODE_PRIVATE)
                      .getString(key, defValue);
    }

    /** 清空所有數據 */
    public static void clear(Context context) {
        context.getSharedPreferences(NAME, Context.MODE_PRIVATE)
               .edit().clear().commit();
    }

    /** 移除指定數據 */
    public static void remove(Context context, String key) {
        context.getSharedPreferences(NAME, Context.MODE_PRIVATE)
               .edit().remove(key).commit();
    }
}

設計重點

  • 透過統一的 XML 名稱 NAME 管理同一組偏好設定,讓讀寫操作集中管理。
  • 為 Long、Int、String、boolean 四種型別各自提供 get/put 方法,呼叫時一目了然。
  • 取值的每個方法都帶有 defValue 預設值參數,當 key 不存在時可回傳合理的預設值。
  • 另外提供 clear() 與 remove(),分別用於清空全部資料與移除單一鍵值。

小提醒:此處使用 commit() 為同步寫入,會阻塞主執行緒;若在意效能,可改用非同步的 apply() 方法。此外,SharedPreferences 不適合儲存大量資料或敏感個資,這類情境建議改用資料庫或加密儲存方案。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © Android教程網 All Rights Reserved