`
ai_longyu
  • 浏览: 479898 次
社区版块
存档分类
最新评论

【Android笔记 九】Android Sharedpreferences实现用户偏好存储

 
阅读更多

在开发应用程序的过程中,有时候我们需要记录用户的偏好,或者用户名密码之类。这就要涉及到数据的存储,android平台下存储数据的方式主要有如下几种方式:

Shared Preferences
Store private primitive data in key-value pairs. 轻量的以键值对的形式进行存储
Internal Storage
Store private data on the device memory. 设备上的文件存储
External Storage
Store public data on the shared external storage. 外部的文件存储,一般指存储在SD卡上的文件,优势是不随程序卸载而删除
SQLite Databases
Store structured data in a private database. 这个比较常见了数据库
Network Connection
Store data on the web with your own network server. 网络获取

那么今天主要和大家分享的是第一种Shareepreference ,这是android提供的一个轻量级的数据存储框架,形式就是键值对的形式,熟悉xml的朋友应该比较习惯这种风格,就是“属性名-属性值”的形式。从名字就可以看出,这个框架主要是用于设置用户的一个偏好,他的一个特点是可以跨session的共享,在多个activity之间可以操作,如果设置特别的权限,其他应用也可以访问。下面就是使用的一个基本方法。

1:获取类型SharedPreferences

主要有两种方式可以获得

  • getSharedPreferences()接受两个参数,第一个是文件标示,第二个是权限,用于创建多个配置文件的场景
  • getPreferences()- 只有文件权限参数,与上一个不同在于只创建一个文件。
今天详细介绍一下第一个方法~

首先看来自官方API的介绍

public abstractSharedPreferencesgetSharedPreferences(Stringname, int mode)

Retrieve and hold the contents of the preferences file 'name', returning a SharedPreferences through which you can retrieve and modify its values. Only one instance of the SharedPreferences object is returned to any callers for the same name, meaning they will see each other's edits as soon as they are made.

解释:该方法用于从上下文,(可以理解为我们的Context文件,相信写过各种服务的朋友并不陌生)取回并维护一个名为name的配置文件。返回一个SharedPreferences对象,我们可以通过这个对象编辑和获取键值。每一个时刻只有一个SharedPreferencesd实例会被调用。效果是,每一个调用者可以立刻看到其他调用者编辑的效果。

Parameters
namemode
Desired preferences file. If a preferences file by this name does not exist, it will be created when you retrieve an editor (SharedPreferences.edit()) and then commit changes (Editor.commit()).
解释:需要的文件名字,如果不存在的话,当你调用editor的时候(用于编辑偏好文件,下面会介绍)会自动创建。
Operating mode. Use 0 orMODE_PRIVATEfor the default operation,MODE_WORLD_READABLEandMODE_WORLD_WRITEABLEto control permissions. The bitMODE_MULTI_PROCESScan also be used if multiple processes are mutating the same SharedPreferences file.MODE_MULTI_PROCESSis always on in apps targetting Gingerbread (Android 2.3) and below, and off by default in later versions.

解释:操作模式 一共有四种,下面逐一解释
Returns
  • Returns the single SharedPreferences instance that can be used to retrieve and modify the preference values.
See Also

有了SharedPreferences对象我们还需要一个Editor来进行偏好的编辑与设置。
Editor主要包含一些putXXX方法,支持booleans, floats, ints, longs, and strings.几种类型,最后完成添加后,一定要调用commit方法或者apply方法进行修改后的提交。

如果想得到value的话就自己直接用SharedPreference类来使用相应的getxxx方法就好了。

不多说了,奉上一段自己临时写的一段非常简单的代码,与大家分享




在最后,我想问一个问题,小O是看了android 2.3的SDK源代码,但是发现,SharedPreference只是一个接口,我并没有找到它的实现,网上也没有相应的解答,希望了解的朋友能及时的联系我,交流一下,谢谢,十一点了,实验室没人了,准备回去睡觉~~

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics