Android SharedPreferences數(shù)據(jù)存儲詳解
前言
Android提供了很多種保存應(yīng)用程序數(shù)據(jù)的方法。其中一種就是用SharedPreferences對象來保存我們私有的鍵值(key-value)數(shù)據(jù)。
所有的邏輯都是基于下面三個類:
- SharedPreferences
- SharedPreferences.Editor
- SharedPreferences.OnSharedPreferenceChangeListener
SharedPreferences
SharedPreferences是其中最重要的。它負(fù)責(zé)獲?。ń馕觯┐鎯Φ臄?shù)據(jù),提供獲取Editor對象的接口和添加或移除OnSharedPreferenceChangeListener的接口。
- 創(chuàng)建SharedPreferences你需要Context對象(也可以是application Context)
- getSharedPreferences方法會解析Preference文件并為它創(chuàng)建一個Map對象
- 你可以用Context提供的幾個模式創(chuàng)建它,強(qiáng)烈建議使用MODE_PRIVATE模式因?yàn)閯?chuàng)建全局可讀寫的文件是比較危險的,可能會導(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)你可以獲取到一個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是一個用來修改SharedPreferences對象值的接口。所有在Editor的修改會進(jìn)行批處理,同時只有你調(diào)用了commit()或者apply()的時候才會復(fù)制到原來的SharedPreferences。
- 用Editor的簡單接口添加值
- 用同步的commit()或速度更快異步的apply()來保存值。實(shí)際上在不同的線程使用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 異步保存 不返回結(jié)果
editor.apply();性能和技巧
SharedPreferences是一個單例對象所以你可以輕易的獲取它的多個引用,它只有在第一次調(diào)用getSharedPreferences的時候打開文件,只為它創(chuàng)建一個引用。(ps:真啰嗦,其實(shí)就是只實(shí)例化一次,后面調(diào)用會越來越快,看下面的例子)
// 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)槭菃卫龑ο竽憧梢噪S意更改它多個實(shí)例的內(nèi)容不用擔(dān)心他們的數(shù)據(jù)會不同
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方法時,它會通過key解析獲取到value然后會把它加到map中,第二次調(diào)用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等操作時間越長。所以推薦把你的數(shù)據(jù)分割成不同的小對象。
你的Preference不會在你的app更新后移除,所以有時候你需要創(chuàng)建一個遷移方案。例如你的app需要在啟動的時候解析本地的JSON,只有在第一次啟動執(zhí)行然后保存boolean的標(biāo)識wasLocalDataLoaded,一段時間后你更新了JSON發(fā)布了一個新版本,用戶會更新app但是他們不會加載新的JSON因?yàn)樗麄冊诘谝粋€版本已經(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ù)存儲詳解的文章就介紹到這了,更多相關(guān)Android SharedPreferences內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
Android優(yōu)化之啟動頁去黑屏實(shí)現(xiàn)秒啟動
本文的內(nèi)容主要是講Android啟動頁優(yōu)化,去黑屏實(shí)現(xiàn)秒啟動的功能,有需要的小伙伴們可以參考學(xué)習(xí)。2016-08-08
Flutter中嵌入Android 原生TextView實(shí)例教程
這篇文章主要給大家介紹了關(guān)于Flutter中嵌入Android 原生TextView的相關(guān)資料,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2020-09-09
Android設(shè)置Activity背景為透明style的簡單方法(必看)
下面小編就為大家?guī)硪黄狝ndroid設(shè)置Activity背景為透明style的簡單方法(必看)。小編覺得挺不錯的,現(xiàn)在就分享給大家,也給大家做個參考。一起跟隨小編過來看看吧2016-10-10
Android中實(shí)現(xiàn)WebView和JavaScript的互相調(diào)用詳解
這篇文章主要給大家介紹了關(guān)于Android中實(shí)現(xiàn)WebView和JavaScript的互相調(diào)用的相關(guān)資料,文中通過示例代碼介紹的非常詳細(xì),對各位Android開發(fā)者們具有一定的參考學(xué)習(xí)價值,需要的朋友下面來一起看看吧。2018-03-03
android 獲取APP的唯一標(biāo)識applicationId的實(shí)例
下面小編就為大家分享一篇android 獲取APP的唯一標(biāo)識applicationId的實(shí)例,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2018-02-02
Android實(shí)現(xiàn)分享長圖并且添加全圖水印
這篇文章主要介紹了Android實(shí)現(xiàn)分享長圖并且添加全圖水印的相關(guān)資料,需要的朋友可以參考下2017-03-03

