首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> 更多程式語言 >> 程式設計綜合問答

Android 開發:跨 Activity 訪問 SharedPreferences 的正確姿勢

     編輯:程式設計綜合問答

問題描述

在 Android 應用中,SharedPreferences 是輕量級數據持久化的首選方案。許多開發者在主 Activity 中成功寫入並讀取數據,但在嘗試從其他 Activity 訪問同一份 SharedPreferences 時卻遇到困難,不知道如何正確獲取實例。

解決方案:使用 PreferenceManager.getDefaultSharedPreferences()

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()

最佳實踐建議

  • 常量定義:將 SharedPreferences 的 Key 定義為 public static final String 放在基類或常量類中,避免硬編碼字符串導致拼寫錯誤。
  • 異步提交:寫入操作優先使用 apply() 而非 commit(),避免阻塞主線程。
  • 類型安全:讀取時提供合理的默認值,防止數據缺失導致崩潰。
  • 封裝工具類:建議封裝 SPUtils 工具類,統一管理讀寫邏輯,提高代碼復用性和可維護性。

進階:自定義 SharedPreferences 文件

若需隔離不同業務模塊的數據,可使用 context.getSharedPreferences("custom_name", Context.MODE_PRIVATE) 創建指定名稱的 SharedPreferences 文件,同樣支持跨組件訪問。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved