SharedPreferences最佳实践
转:http://blog.csdn.net/xushuaic/article/details/24513599
笔记摘要:该文章是我在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 file
 - 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.
 - 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
SharedPreference.Editor 是一个用于修改SharedPreferences值的接口。在Editor里所做的所有变更都会被批处理,但是不会立即覆盖到原始的SharedPreferences中,直到你调用了commit()或者apply()。
- 使用简单的接口保存值到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
 - boolean result = editor.commit();
 - // do the same as commit() but asynchronously (faster but not safely)
 - // returns nothing
 - editor.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 15
 - int 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();
 - }
 
SharedPreferences最佳实践的更多相关文章
- ASP.NET跨平台最佳实践
		
前言 八年的坚持敌不过领导的固执,最终还是不得不阔别已经成为我第二语言的C#,转战Java阵营.有过短暂的失落和迷茫,但技术转型真的没有想象中那么难.回头审视,其实单从语言本身来看,C#确实比Java ...
 - 《AngularJS深度剖析与最佳实践》简介
		
由于年末将至,前阵子一直忙于工作的事务,不得已暂停了微信订阅号的更新,我将会在后续的时间里尽快的继续为大家推送更多的博文.毕竟一个人的力量微薄,精力有限,希望大家能理解,仍然能一如既往的关注和支持sh ...
 - ASP.NET MVC防范CSRF最佳实践
		
XSS与CSRF 哈哈,有点标题党,但我保证这篇文章跟别的不太一样. 我认为,网站安全的基础有三块: 防范中间人攻击 防范XSS 防范CSRF 注意,我讲的是基础,如果更高级点的话可以考虑防范机器人刷 ...
 - 快速web开发中的前后端框架选型最佳实践
		
这个最佳实践是我目前人在做的一个站点,主要功能: oauth登录 发布文章(我称为"片段"),片段可以自定义一些和内容有关的指标,如“文中人物:12”.支持自定义排版.插图.建立相 ...
 - Spring Batch在大型企业中的最佳实践
		
在大型企业中,由于业务复杂.数据量大.数据格式不同.数据交互格式繁杂,并非所有的操作都能通过交互界面进行处理.而有一些操作需要定期读取大批量的数据,然后进行一系列的后续处理.这样的过程就是" ...
 - Atitit.log日志技术的最佳实践attilax总结
		
Atitit.log日志技术的最佳实践attilax总结 1. 日志的意义与作用1 1.1. 日志系统是一种不可或缺的单元测试,跟踪调试工具1 2. 俩种实现[1]日志系统作为一种服务进程存在 [2] ...
 - PHP核心技术与最佳实践——全局浏览
		
难得买到并喜欢一本好书,‘PHP核心技术与最佳实践’. 几天时间,先看了个大概,总结一下整体是什么样子的,怎么看怎么学. 1.总共14章: 2.第1.2章讲PHP的OOP: 其中第一章侧重于PHP的O ...
 - Abp集成Swagger的最佳实践
		
1.在项目中添加nuget包 Abp.Web.Api.SwaggerTool 2.在项目Abp模块的DependsOn添加AbpWebApiSwaggerToolModule Run It,启动项目, ...
 - MySQL · 答疑解惑 · MySQL 锁问题最佳实践
		
http://mysql.taobao.org/monthly/2016/03/10/ 前言 最近一段时间处理了较多锁的问题,包括锁等待导致业务连接堆积或超时,死锁导致业务失败等,这类问题对业务可能会 ...
 
随机推荐
- C#委托 Lamda表达式
			
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.T ...
 - (八)Android广播接收器BroadcastReceiver
			
一.使用Broadcast Reciver 1.右击java文件夹,new->other->Broadcast Receiver后会在AndroidManifest.xml文件中生成一个r ...
 - locate linux文件查找命令
			
locate 让使用者可以很快速的搜寻档案系统内是否有指定的档案.其方法是先建立一个包括系统内所有档案名称及路径的数据库,之后当寻找时就只需查询这个数据库,而不必实际深入档案系统之中了.在一般的 di ...
 - linux 删除和安装java
			
一.jdk1.4卸载 由于redhat Enterprise 5 中自带安装了jdk1.4的,所以在安装jdk1.6前我把jdk1.4的卸了,步骤如下: 1.打开终端输入#rpm -qa | gr ...
 - Android 尺寸 神图
 - skynet的流程1
			
logpath = "."harbor = 1address = "127.0.0.1:2526"master = "127.0.0.1:2013&q ...
 - 推荐大家使用的CSS书写规范、顺序(转载)
			
转自:http://www.admin10000.com/document/2979.html 写了这么久的CSS,但大部分前端er都没有按照良好的CSS书写规范来写CSS代码,这样会影响代码的阅读体 ...
 - Qt新建线程的方法(四种办法,很详细,有截图)
			
看了不少Qt线程的东西,下面总结一下Qt新建一个线程的方法. 一.继承QThread 继承QThread,这应该是最常用的方法了.我们可以通过重写虚函数void QThread::run ()实现我们 ...
 - 【第一篇章-android平台buffer播放探索】native media
			
在android平台,从4.0开始,提出了openmax架构,所以在DNK的R7版本中有了openmax AL层播放的DEMO即native media,这个DEMO就是读本地文件,然后把所读buff ...
 - 【Daily】 2014-4-28
			
KEEP GOING 表达产品想法, 探讨产品问题, 倾听可能性问题. 一次就做好, 有成果展示, 主动展示 先确立图, 后确立代码. Hold dream, and never let it go ...