SharedPreferences最佳实践

来源:互联网 发布:淘宝分销需要交钱吗 编辑:程序博客网 时间:2024/06/05 02:12

笔记摘要:该文章是我在Android Weekly中看到的,以前也一直用SharedPreferences,不过一直只是会用,并没有深入研究下,既然看过了这篇文章,就翻下记录下来对自己理解也会有帮助,和朋友们分享下。另外提一下Android Weekly,这是一个每周发布一次Android行业最新动态的国外网站,其中的LatestIssue和ToolBox模块你可以关注下,LatestIssue会发布一下比较优秀的新的开源项目,每周我都会看一下,之后一定就在gitHub上找到并start上了。ToolBox模块就是一些好的开源项目了,不过更新的不怎么频繁,大家也可以看下。

先贴上作者发布到GitHub的源代码:Best Practice. SharedPreferences.
原文地址:Best Practice ,以下是译文。

Android开发者有很多方式都可以存储应用的数据。其中之一是SharedPreference对象,该对象可以通过key-value的形式保存私有的数据。

所有的逻辑依赖下面3个类
SharedPreferences
SharedPreferences.Editor
SharedPreferences.OnSharedPreferenceChangeListener

SharedPreferences
SharedPreferences在这3个类中是最主要的。它负提供了获取Editor对象的接口和添加删除的监听:OnSharedPreferenceChangeListener

- 创建SharedPreferences 时,你需要Context对象
- getSharedPreferences方法用于解析Preference文件并为其创建Map对象。
- 你可以通过提供的Context创建不同的模式,强烈建议使用MODE_PRIVATE,因为创建任意可读取的文件是非常危险的,可能
会在应用中导致一些安全问题。

// parse Preference fileSharedPreferences preferences = context.getSharedPreferences("com.example.app", Context.MODE_PRIVATE); // get values from Mappreferences.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.Map<String, ?> all = preferences.getAll(); // get Editor objectSharedPreferences.Editor editor = preferences.edit(); //add on Change Listenerpreferences.registerOnSharedPreferenceChangeListener(mListener); //remove on Change Listenerpreferences.unregisterOnSharedPreferenceChangeListener(mListener); // listener exampleSharedPreferences.OnSharedPreferenceChangeListener mOnSharedPreferenceChangeListener        = new SharedPreferences.OnSharedPreferenceChangeListener() {    @Override    public void onSharedPreferenceChanged(SharedPreferences sharedPreferences, String key) {    }};

Editor
SharedPreference.Editor 是一个用于修改SharedPreferences值的接口。在Editor里所做的所有变更都会被批处理,但是不会立即覆盖到原始的SharedPreferences中,直到你调用了commit()或者apply()。

- 使用简单的接口保存值到Editor中
- 使用commit()同步或者apply()异步保存值(异步更快)。事实上,在不同的线程中使用commit()更安全,这也正是我倾向于使用commit()的原因。
- 通过remove()移除单一的值或者通过clear删除所有的值。

// get Editor objectSharedPreferences.Editor editor = preferences.edit(); // put values in editoreditor.putBoolean("key", value);editor.put..("key", value); // remove single value by keyeditor.remove("key"); // remove all valueseditor.clear(); // commit your putted values to the SharedPreferences object synchronously// returns true if successboolean result = editor.commit(); // do the same as commit() but asynchronously (faster but not safely)// returns nothingeditor.apply();



性能和贴士
SharedPreferences 是一个单例对象,因此,你可以在很多地方引用它,获取也很容易。它只会在第一次调用getSharedPreferences的时候打开或者为其创建一个引用。
// There are 1000 String values in preferences SharedPreferences first = context.getSharedPreferences("com.example.app", Context.MODE_PRIVATE);// call time = 4 milliseconds SharedPreferences second = context.getSharedPreferences("com.example.app", Context.MODE_PRIVATE);// call time = 0 milliseconds SharedPreferences third = context.getSharedPreferences("com.example.app", Context.MODE_PRIVATE);// call time = 0 milliseconds

由于SharedPreferences是一个单例对象,你不用担心任意的变更会导致数据的不一致。

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

当你第一次调用get方法的时候,它会通过key解析值,并把这些值添加到map集合中。因此对于下面的second调用它,只会从map中获取,而不再解析。
first.getString("key", null)// call time = 147 milliseconds first.getString("key", null)// call time = 0 milliseconds second.getString("key", null)// call time = 0 milliseconds third.getString("key", null)// call time = 0 milliseconds
记住Preference对象越大,对于get,commit,apply和clear的操作时间将会越长。因此强烈建议在不同的小对象中分开操作你的数据。
你的preference在应用更新的时候不会被移除。因此,这时候,你需要创建一些新的升级规则。比如你有一个应用,它会在启动的时候解析本地的JSON数据,在你第一次启动后,你决定保存wasLocalDataLoaded 标记。在之后的多次更新JSON数据和发布新版本的时候,用户只会更新它们的应用而不会再加载新的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 是以XML的格式保存在你的data文件夹中的
// 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();    }}
0 0
原创粉丝点击