SharedPreferences 是 Android 輕量級鍵值對儲存方案,適用於保存使用者偏好設定、登入狀態、小量結構化資料。本文提供完整的讀寫封裝工具類,涵蓋同步/非同步提交、型別安全讀取、預設值處理、刪除與清空等常用操作。
public class PrefsHelper {
private static final String PREF_NAME = "app_config";
private static SharedPreferences sPrefs;
private static SharedPreferences.Editor sEditor;
// 單例模式初始化
public static void init(Context context) {
if (sPrefs == null) {
sPrefs = context.getSharedPreferences(PREF_NAME, Context.MODE_PRIVATE);
sEditor = sPrefs.edit();
}
}
// 同步寫入 (apply 非同步,commit 同步並回傳 boolean)
public static void putString(String key, String value) { sEditor.putString(key, value).apply(); }
public static void putInt(String key, int value) { sEditor.putInt(key, value).apply(); }
public static void putLong(String key, long value) { sEditor.putLong(key, value).apply(); }
public static void putFloat(String key, float value) { sEditor.putFloat(key, value).apply(); }
public static void putBoolean(String key, boolean value) { sEditor.putBoolean(key, value).apply(); }
public static void putStringSet(String key, Set value) { sEditor.putStringSet(key, value).apply(); }
// 型別安全讀取 (提供預設值)
public static String getString(String key, String defValue) { return sPrefs.getString(key, defValue); }
public static int getInt(String key, int defValue) { return sPrefs.getInt(key, defValue); }
public static long getLong(String key, long defValue) { return sPrefs.getLong(key, defValue); }
public static float getFloat(String key, float defValue) { return sPrefs.getFloat(key, defValue); }
public static boolean getBoolean(String key, boolean defValue) { return sPrefs.getBoolean(key, defValue); }
public static Set getStringSet(String key, Set defValue) { return sPrefs.getStringSet(key, defValue); }
// 刪除單一鍵 / 全部清空
public static void remove(String key) { sEditor.remove(key).apply(); }
public static void clear() { sEditor.clear().apply(); }
// 判斷鍵是否存在
public static boolean contains(String key) { return sPrefs.contains(key); }
// 註冊變更監聽器
public static void registerOnSharedPreferenceChangeListener(SharedPreferences.OnSharedPreferenceChangeListener listener) {
sPrefs.registerOnSharedPreferenceChangeListener(listener);
}
public static void unregisterOnSharedPreferenceChangeListener(SharedPreferences.OnSharedPreferenceChangeListener listener) {
sPrefs.unregisterOnSharedPreferenceChangeListener(listener);
}
}
// Application.onCreate() 初始化一次
PrefsHelper.init(this);
// 寫入
PrefsHelper.putString("user_token", "abc123");
PrefsHelper.putBoolean("is_logged_in", true);
PrefsHelper.putInt("theme_mode", 2); // 0=跟隨系統, 1=淺色, 2=深色
// 讀取
String token = PrefsHelper.getString("user_token", "");
boolean loggedIn = PrefsHelper.getBoolean("is_logged_in", false);
int theme = PrefsHelper.getInt("theme_mode", 0);
// 監聽主題變更
PrefsHelper.registerOnSharedPreferenceChangeListener((prefs, key) -> {
if ("theme_mode".equals(key)) {
int newTheme = prefs.getInt(key, 0);
applyTheme(newTheme);
}
});
apply() 非同步寫入磁碟,不阻塞主執行緒,效能優;commit() 同步寫入並回傳成功與否,需在背景執行緒呼叫。推薦統一用 apply()。Context.MODE_MULTI_PROCESS (已棄用) 或改用 DataStore / ContentProvider / MMKV。pref_user_token、pref_theme_mode,避免衝突。Google 官方推薦使用 DataStore 取代 SharedPreferences:
// Preferences DataStore 依賴
implementation "androidx.datastore:datastore-preferences:1.0.0"
// 使用
val dataStore = context.createDataStore("settings")
val EXAMPLE_COUNTER = intPreferencesKey("example_counter")
suspend fun incrementCounter() {
dataStore.edit { settings ->
val current = settings[EXAMPLE_COUNTER] ?: 0
settings[EXAMPLE_COUNTER] = current + 1
}
}
新專案請直接上 DataStore;存量專案可漸進式遷移,SharedPreferences 仍可共存使用。