在 Android 應用中,SharedPreferences 是輕量級數據持久化的首選方案。許多開發者在主 Activity 中成功寫入並讀取數據,但在嘗試從其他 Activity 訪問同一份 SharedPreferences 時卻遇到困難,不知道如何正確獲取實例。
Android 提供了 PreferenceManager.getDefaultSharedPreferences(Context) 靜態方法,可在應用的任何 Context(包括任意 Activity、Service)中獲取默認的共享偏好設定實例。這份默認 SharedPreferences 文件以應用包名命名,全局唯一,天然支持跨組件訪問。
// 在任意 Activity 中獲取默認 SharedPreferences
SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(this);
// 讀取數據(假設 KEY 定義在 MainActivity 中為 public static final)
if (sp.contains(MainActivity.GAME_PREFERENCES_SHOP)) {
String shopName = sp.getString(MainActivity.GAME_PREFERENCES_SHOP, "");
tv2.setText(shopName);
}
// 寫入數據
SharedPreferences.Editor editor = sp.edit();
editor.putString(MainActivity.GAME_PREFERENCES_SHOP, newShopName);
editor.apply(); // 推薦使用 apply() 異步提交,性能優於 commit()
public static final String 放在基類或常量類中,避免硬編碼字符串導致拼寫錯誤。apply() 而非 commit(),避免阻塞主線程。SPUtils 工具類,統一管理讀寫邏輯,提高代碼復用性和可維護性。若需隔離不同業務模塊的數據,可使用 context.getSharedPreferences("custom_name", Context.MODE_PRIVATE) 創建指定名稱的 SharedPreferences 文件,同樣支持跨組件訪問。