1、SharedPreferences的简单介绍

        应用程序在运行的时候,可能会随着用户的使用而保持该用户的配置信息,如上次播放时的eq设置,音量设置,上网的cookies信息等等,这些小量 的信息可以通过SharedPreferences来保持,通过SharedPreferences保持的数据为一个XML文件,位于应用程序的私有文件夹。

2、具体操作方法

获取SharedPreferences,可以通过以下方法获取

public SharedPreferences getSharedPreferences (String name, int mode)

Since: API Level 1

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.

Parameters
name 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()).
mode Operating mode. Use 0 or MODE_PRIVATE for the default operation,MODE_WORLD_READABLE andMODE_WORLD_WRITEABLE to control permissions. The bitMODE_MULTI_PROCESS can also be used if multiple processes are mutating the same SharedPreferences file.MODE_MULTI_PROCESS is 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.

 

参数简述:

Name————获得SharedPreferences之后,将会在应用程序的私有文件夹中保存着一个XML文件,第一个参数name就是这个文件名字。

Mode————XML文件的保存模式,默认为0,也就是MODE_PRIVATE

 

3、简单的demo

通过service的一个音乐播放例子,“播放”与“暂停”两个按钮

暂停之后,保持播放进度到SharedPreferences里面,然后再次播放的话,读取进度值进行音乐播放。

稳定

产品高可用性高并发

贴心

项目群及时沟通

专业

产品经理1v1支持

快速

MVP模式小步快跑

承诺

我们选择声誉

坚持

10年专注高端品质开发
  • 返回顶部