欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

Android SharedPreferences數據存儲詳解

 更新時間:2022年11月15日 09:23:16   作者:后端碼匠  
SharedPreferences是安卓平臺上一個輕量級的存儲類,用來保存應用的一些常用配置,比如Activity狀態(tài),Activity暫停時,將此activity的狀態(tài)保存到SharedPereferences中;當Activity重載,系統(tǒng)回調方法onSaveInstanceState時,再從SharedPreferences中將值取出

前言

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

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

  • SharedPreferences
  • SharedPreferences.Editor
  • SharedPreferences.OnSharedPreferenceChangeListener

SharedPreferences

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

  • 創(chuàng)建SharedPreferences你需要Context對象(也可以是application Context)
  • getSharedPreferences方法會解析Preference文件并為它創(chuàng)建一個Map對象
  • 你可以用Context提供的幾個模式創(chuàng)建它,強烈建議使用MODE_PRIVATE模式因為創(chuàng)建全局可讀寫的文件是比較危險的,可能會導致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 添加監(jiān)聽器
  preferences.registerOnSharedPreferenceChangeListener(mListener);
  // remove on Change Listener 取消監(jiān)聽器
  preferences.unregisterOnSharedPreferenceChangeListener(mListener);
  // listener example 監(jiān)聽器例子
  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的時候打開文件,只為它創(chuàng)建一個引用。(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更新后移除,所以有時候你需要創(chuàng)建一個遷移方案。例如你的app需要在啟動的時候解析本地的JSON,只有在第一次啟動執(zhí)行然后保存boolean的標識wasLocalDataLoaded,一段時間后你更新了JSON發(fā)布了一個新版本,用戶會更新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 我們自己創(chuàng)建的
  /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();
        }
    }

到此這篇關于Android SharedPreferences數據存儲詳解的文章就介紹到這了,更多相關Android SharedPreferences內容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關文章希望大家以后多多支持腳本之家!

相關文章

  • Java ArrayList源碼深入分析

    Java ArrayList源碼深入分析

    ArrayList 類是一個可以動態(tài)修改的數組,與普通數組的區(qū)別就是它是沒有固定大小的限制,我們可以添加或刪除元素。ArrayList 繼承了 AbstractList,并實現了List接口
    2022-08-08
  • Android優(yōu)化之啟動頁去黑屏實現秒啟動

    Android優(yōu)化之啟動頁去黑屏實現秒啟動

    本文的內容主要是講Android啟動頁優(yōu)化,去黑屏實現秒啟動的功能,有需要的小伙伴們可以參考學習。
    2016-08-08
  • Android中比較兩個圖片是否一致的問題

    Android中比較兩個圖片是否一致的問題

    這篇文章主要介紹了Android中比較兩個圖片是否一致的問題,本文通過實例代碼給大家介紹的非常詳細,對大家的學習或工作具有一定的參考借鑒價值,需要的朋友可以參考下
    2020-10-10
  • Flutter中嵌入Android 原生TextView實例教程

    Flutter中嵌入Android 原生TextView實例教程

    這篇文章主要給大家介紹了關于Flutter中嵌入Android 原生TextView的相關資料,文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友們下面隨著小編來一起學習學習吧
    2020-09-09
  • Android設置Activity背景為透明style的簡單方法(必看)

    Android設置Activity背景為透明style的簡單方法(必看)

    下面小編就為大家?guī)硪黄狝ndroid設置Activity背景為透明style的簡單方法(必看)。小編覺得挺不錯的,現在就分享給大家,也給大家做個參考。一起跟隨小編過來看看吧
    2016-10-10
  • Android中實現WebView和JavaScript的互相調用詳解

    Android中實現WebView和JavaScript的互相調用詳解

    這篇文章主要給大家介紹了關于Android中實現WebView和JavaScript的互相調用的相關資料,文中通過示例代碼介紹的非常詳細,對各位Android開發(fā)者們具有一定的參考學習價值,需要的朋友下面來一起看看吧。
    2018-03-03
  • Kotlin Thread線程與UI更新詳解

    Kotlin Thread線程與UI更新詳解

    本篇主要介紹Kotlin中Thread線程與UI更新,注意不是協(xié)程而是線程。Kotlin本身是支持線程的。同時協(xié)程也是運行在線程中的
    2022-12-12
  • android 獲取APP的唯一標識applicationId的實例

    android 獲取APP的唯一標識applicationId的實例

    下面小編就為大家分享一篇android 獲取APP的唯一標識applicationId的實例,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧
    2018-02-02
  • Android實現分享長圖并且添加全圖水印

    Android實現分享長圖并且添加全圖水印

    這篇文章主要介紹了Android實現分享長圖并且添加全圖水印的相關資料,需要的朋友可以參考下
    2017-03-03
  • Android自定義View模仿虎撲直播界面的打賞按鈕功能

    Android自定義View模仿虎撲直播界面的打賞按鈕功能

    這篇文章主要介紹了Android自定義View模仿虎撲直播界面的打賞按鈕功能,文中介紹的非常詳細,對各位Android開發(fā)者們具有一定的參考價值,需要的朋友們下面來一起看看吧。
    2017-04-04

最新評論