亚洲乱码中文字幕综合,中国熟女仑乱hd,亚洲精品乱拍国产一区二区三区,一本大道卡一卡二卡三乱码全集资源,又粗又黄又硬又爽的免费视频

Android SharedPreferences數(shù)據(jù)存儲(chǔ)詳解

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

前言

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

所有的邏輯都是基于下面三個(gè)類:

  • SharedPreferences
  • SharedPreferences.Editor
  • SharedPreferences.OnSharedPreferenceChangeListener

SharedPreferences

SharedPreferences是其中最重要的。它負(fù)責(zé)獲?。ń馕觯┐鎯?chǔ)的數(shù)據(jù),提供獲取Editor對(duì)象的接口和添加或移除OnSharedPreferenceChangeListener的接口。

  • 創(chuàng)建SharedPreferences你需要Context對(duì)象(也可以是application Context)
  • getSharedPreferences方法會(huì)解析Preference文件并為它創(chuàng)建一個(gè)Map對(duì)象
  • 你可以用Context提供的幾個(gè)模式創(chuàng)建它,強(qiáng)烈建議使用MODE_PRIVATE模式因?yàn)閯?chuàng)建全局可讀寫的文件是比較危險(xiǎn)的,可能會(huì)導(dǎo)致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文件轉(zhuǎn)換成map)你可以獲取到一個(gè)map但是小心點(diǎn)最好不要修改map或它的內(nèi)容
  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是一個(gè)用來修改SharedPreferences對(duì)象值的接口。所有在Editor的修改會(huì)進(jìn)行批處理,同時(shí)只有你調(diào)用了commit()或者apply()的時(shí)候才會(huì)復(fù)制到原來的SharedPreferences。

  • 用Editor的簡(jiǎn)單接口添加值
  • 用同步的commit()或速度更快異步的apply()來保存值。實(shí)際上在不同的線程使用commit()時(shí)會(huì)更安全。這是為什么我喜歡用commit()
  • 刪除單個(gè)值用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 異步保存 不返回結(jié)果
  editor.apply();

性能和技巧

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

  // 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

因?yàn)槭菃卫龑?duì)象你可以隨意更改它多個(gè)實(shí)例的內(nèi)容不用擔(dān)心他們的數(shù)據(jù)會(huì)不同

  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

當(dāng)你第一次調(diào)用get方法時(shí),它會(huì)通過key解析獲取到value然后會(huì)把它加到map中,第二次調(diào)用get會(huì)直接從map拿出,不用解析。

  first.getString("key", null)  
  // call time = 147 milliseconds 第一次拿需要解析比較慢,然后會(huì)放到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對(duì)象它的get,commit,apply,remove和clear等操作時(shí)間越長(zhǎng)。所以推薦把你的數(shù)據(jù)分割成不同的小對(duì)象。

你的Preference不會(huì)在你的app更新后移除,所以有時(shí)候你需要?jiǎng)?chuàng)建一個(gè)遷移方案。例如你的app需要在啟動(dòng)的時(shí)候解析本地的JSON,只有在第一次啟動(dòng)執(zhí)行然后保存boolean的標(biāo)識(shí)wasLocalDataLoaded,一段時(shí)間后你更新了JSON發(fā)布了一個(gè)新版本,用戶會(huì)更新app但是他們不會(huì)加載新的JSON因?yàn)樗麄冊(cè)诘谝粋€(gè)版本已經(jīng)做了。

  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 默認(rèn)
  /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();
        }
    }

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

相關(guān)文章

  • Java ArrayList源碼深入分析

    Java ArrayList源碼深入分析

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

    Android優(yōu)化之啟動(dòng)頁去黑屏實(shí)現(xiàn)秒啟動(dòng)

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

    Android中比較兩個(gè)圖片是否一致的問題

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

    Flutter中嵌入Android 原生TextView實(shí)例教程

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

    Android設(shè)置Activity背景為透明style的簡(jiǎn)單方法(必看)

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

    Android中實(shí)現(xiàn)WebView和JavaScript的互相調(diào)用詳解

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

    Kotlin Thread線程與UI更新詳解

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

    android 獲取APP的唯一標(biāo)識(shí)applicationId的實(shí)例

    下面小編就為大家分享一篇android 獲取APP的唯一標(biāo)識(shí)applicationId的實(shí)例,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過來看看吧
    2018-02-02
  • Android實(shí)現(xiàn)分享長(zhǎng)圖并且添加全圖水印

    Android實(shí)現(xiàn)分享長(zhǎng)圖并且添加全圖水印

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

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

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

最新評(píng)論