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/ 前言 最近一段时间处理了较多锁的问题,包括锁等待导致业务连接堆积或超时,死锁导致业务失败等,这类问题对业务可能会 ...
随机推荐
- HibernateTemplate 常用方法
HibernateTemplate 提供非常多的常用方法来完成基本的操作,比如通常的增加.删除.修改.查询等操作,Spring2.0更增加对命名SQL查询的支持,也增加对分页的支 持.大部分情况下,使 ...
- C++ extern "C",C与C++的区别
1. C++保留了一部分过程式语言的特点,因而它可以定义不属于任何类的全局变量和函数.但是,C++毕竟是一种面向对象的程序设计语言,为了支持函数的重载,C++对全局函数的处理方式与C有明显的不同. 2 ...
- C指针--通过二级指针往回拉数据
现在有这种需求,在main函数中建立一个二叉树的root结点的指针,在tree_create函数中malloc或者new一个二叉树结点,然后在main函数中能正常的访问这个新建的结点. 注:这里的tr ...
- mysql 更新 语句中 的 safe_mode
在mysql5中,可以设置safe mode,比如在一个更新语句中UPDATE table_name SET bDeleted=0;执行时会错误,报:You are using safe update ...
- python程序不支持中文
SyntaxError: Non-ASCII character '\xe8' in file delete.py on line 4, but no encoding declared; see h ...
- linux 生产环境搭建
Linux基础命令杂记 今天又一次搞Linux生产环境搭建.这是种步骤很多,很繁琐而且又不得不做的事情.虽然做过很多次,但还是有很多步骤.命令不记得,每一次到处找资料很麻烦,于是将一些步骤记下,以 ...
- 小米4c刷机
[测评] 试用小米4c最新波兰开发版 http://www.miui.com/thread-3048163-1-1.html [教程] 小米4C刷第三方recovery 以及ROOT教程 http:/ ...
- 《UNIX网络编程》UDP客户端服务器:消息回显
udp写的程序相比tcp简单一些,在socket()与bind()之后,不需要connect(),accept()等步骤,直接简化为了sendto()与recvfrom(). 编译运行同前面的tcp. ...
- Android04-UI01常用控件
1.常见控件的使用: TextView Button EditText ImageView 1.TextView <TextView android:id="@+id/text_v ...
- 转: JavaScript函数式编程(二)
转: JavaScript函数式编程(二) 作者: Stark伟 上一篇文章里我们提到了纯函数的概念,所谓的纯函数就是,对于相同的输入,永远会得到相同的输出,而且没有任何可观察的副作用,也不依赖外部环 ...