日本免费高清视频-国产福利视频导航-黄色在线播放国产-天天操天天操天天操天天操|www.shdianci.com

學無先后,達者為師

網站首頁 編程語言 正文

Android?SharedPreferences數據存儲詳解_Android

作者:后端碼匠 ? 更新時間: 2022-12-12 編程語言

前言

Android提供了很多種保存應用程序數據的方法。其中一種就是用SharedPreferences對象來保存我們私有的鍵值(key-value)數據。

所有的邏輯都是基于下面三個類:

  • SharedPreferences
  • SharedPreferences.Editor
  • SharedPreferences.OnSharedPreferenceChangeListener

SharedPreferences

SharedPreferences是其中最重要的。它負責獲取(解析)存儲的數據,提供獲取Editor對象的接口和添加或移除OnSharedPreferenceChangeListener的接口。

  • 創建SharedPreferences你需要Context對象(也可以是application Context)
  • getSharedPreferences方法會解析Preference文件并為它創建一個Map對象
  • 你可以用Context提供的幾個模式創建它,強烈建議使用MODE_PRIVATE模式因為創建全局可讀寫的文件是比較危險的,可能會導致app的安全漏洞。
  / parse Preference file 解析Preference文件
  SharedPreferences preferences = context.getSharedPreferences("com.example.app", Context.MODE_PRIVATE);
  // get values from Map
  preferences.getBoolean("key", defaultValue)  
  preferences.get..("key", defaultValue)
  // you can get all Map but be careful you must not modify the collection returned by this
  // method, or alter any of its contents.
  //(Preference文件轉換成map)你可以獲取到一個map但是小心點最好不要修改map或它的內容
  Map<String, ?> all = preferences.getAll();
  // get Editor object
  SharedPreferences.Editor editor = preferences.edit();
  // add on Change Listener 添加監聽器
  preferences.registerOnSharedPreferenceChangeListener(mListener);
  // remove on Change Listener 取消監聽器
  preferences.unregisterOnSharedPreferenceChangeListener(mListener);
  // listener example 監聽器例子
  SharedPreferences.OnSharedPreferenceChangeListener mOnSharedPreferenceChangeListener  
          = new SharedPreferences.OnSharedPreferenceChangeListener() {
      @Override
      public void onSharedPreferenceChanged(SharedPreferences sharedPreferences, String key) {
      }
  };

Editor

SharedPreferences.Editor是一個用來修改SharedPreferences對象值的接口。所有在Editor的修改會進行批處理,同時只有你調用了commit()或者apply()的時候才會復制到原來的SharedPreferences。

  • 用Editor的簡單接口添加值
  • 用同步的commit()或速度更快異步的apply()來保存值。實際上在不同的線程使用commit()時會更安全。這是為什么我喜歡用commit()
  • 刪除單個值用remove,刪除所有值用clear()
  // get Editor object
  SharedPreferences.Editor editor = preferences.edit();
  // put values in editor
  editor.putBoolean("key", value);  
  editor.put..("key", value);
  // remove single value by key
  editor.remove("key");
  // remove all values
  editor.clear();
  // commit your putted values to the SharedPreferences object synchronously
  // returns true if success 同步提交保存 成功返回true
  boolean result = editor.commit();
  // do the same as commit() but asynchronously (faster but not safely)
  // returns nothing 異步保存 不返回結果
  editor.apply();

性能和技巧

SharedPreferences是一個單例對象所以你可以輕易的獲取它的多個引用,它只有在第一次調用getSharedPreferences的時候打開文件,只為它創建一個引用。(ps:真啰嗦,其實就是只實例化一次,后面調用會越來越快,看下面的例子)

  // There are 1000 String values in preferences
  SharedPreferences first = context.getSharedPreferences("com.example.app", Context.MODE_PRIVATE);  
  // call time = 4 milliseconds第一次讀取文件花了4毫秒
  SharedPreferences second = context.getSharedPreferences("com.example.app", Context.MODE_PRIVATE);  
  // call time = 0 milliseconds第二次0
  SharedPreferences third = context.getSharedPreferences("com.example.app", Context.MODE_PRIVATE);  
  // call time = 0 milliseconds第三次0

因為是單例對象你可以隨意更改它多個實例的內容不用擔心他們的數據會不同

  first.edit().putInt("key",15).commit();
  int firstValue = first.getInt("key",0)); // firstValue is 15  
  int secondValue = second.getInt("key",0)); // secondValue is also 15

當你第一次調用get方法時,它會通過key解析獲取到value然后會把它加到map中,第二次調用get會直接從map拿出,不用解析。

  first.getString("key", null)  
  // call time = 147 milliseconds 第一次拿需要解析比較慢,然后會放到map中
  first.getString("key", null)  
  // call time = 0 milliseconds 第二次直接從map中拿 ,不用解析 很快
  second.getString("key", null)  
  // call time = 0 milliseconds 和第二次一樣
  third.getString("key", null)  
  // call time = 0 milliseconds

記住越大的Preference對象它的get,commit,apply,remove和clear等操作時間越長。所以推薦把你的數據分割成不同的小對象。

你的Preference不會在你的app更新后移除,所以有時候你需要創建一個遷移方案。例如你的app需要在啟動的時候解析本地的JSON,只有在第一次啟動執行然后保存boolean的標識wasLocalDataLoaded,一段時間后你更新了JSON發布了一個新版本,用戶會更新app但是他們不會加載新的JSON因為他們在第一個版本已經做了。

  public class MigrationManager {  
      private final static String KEY_PREFERENCES_VERSION = "key_preferences_version";
      private final static int PREFERENCES_VERSION = 2;
      public static void migrate(Context context) {
          SharedPreferences preferences = context.getSharedPreferences("pref", Context.MODE_PRIVATE);
          checkPreferences(preferences);
      }
      private static void checkPreferences(SharedPreferences thePreferences) {
          final double oldVersion = thePreferences.getInt(KEY_PREFERENCES_VERSION, 1);
          if (oldVersion < PREFERENCES_VERSION) {
              final SharedPreferences.Editor edit = thePreferences.edit();
              edit.clear();
              edit.putInt(KEY_PREFERENCES_VERSION, currentVersion);
              edit.commit();
          }
      }
  }

SharedPreferences保存在app的data文件夾下xml文件里面

? // yours preferences 我們自己創建的
? /data/data/YOUR_PACKAGE_NAME/shared_prefs/YOUR_PREFS_NAME.xml
? // default preferences 默認
? /data/data/YOUR_PACKAGE_NAME/shared_prefs/YOUR_PACKAGE_NAME_preferences.xml

示例代碼

    public class PreferencesManager {
        private static final String PREF_NAME = "com.example.app.PREF_NAME";
        private static final String KEY_VALUE = "com.example.app.KEY_VALUE";
        private static PreferencesManager sInstance;
        private final SharedPreferences mPref;
        private PreferencesManager(Context context) {
            mPref = context.getSharedPreferences(PREF_NAME, Context.MODE_PRIVATE);
        }
        public static synchronized void initializeInstance(Context context) {
            if (sInstance == null) {
                sInstance = new PreferencesManager(context);
            }
        }
        public static synchronized PreferencesManager getInstance() {
            if (sInstance == null) {
                throw new IllegalStateException(PreferencesManager.class.getSimpleName() +
                        " is not initialized, call initializeInstance(..) method first.");
            }
            return sInstance;
        }
        public void setValue(long value) {
            mPref.edit()
                    .putLong(KEY_VALUE, value)
                    .commit();
        }
        public long getValue() {
            return mPref.getLong(KEY_VALUE, 0);
        }
        public void remove(String key) {
            mPref.edit()
                    .remove(key)
                    .commit();
        }
        public boolean clear() {
            return mPref.edit()
                    .clear()
                    .commit();
        }
    }

原文鏈接:https://codingce.blog.csdn.net/article/details/126267833

欄目分類
最近更新