http://blog.csdn.net/ah200614435/article/details/7869681

一直迷惑于这三个方法的关系,最近忙完项目,好好的分析一下。

如果你熟悉Context那么你可能知道Context当中有这样一个方法:(关于Context的说明)

一、getSharedPreferences(String name, int mode)

abstract SharedPreferences  getSharedPreferences(String name, 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.

得到名为‘name’的偏好文件。同时你可以更改和返回他的值。任何调用者在调用同样名字的偏好文件时只有一个实例返回,这就意味着这些调用者都可以看到其他调用者做出的更改。

这个函数的参数如下:

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 bit MODE_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.

name为本组件的配置文件名( 自己定义,也就是一个文件名),当这个文件不存在时,直接创建,如果已经存在,则直接使用,

mode为操作模式,默认的模式为0或MODE_PRIVATE,还可以使用MODE_WORLD_READABLE和MODE_WORLD_WRITEABLE
mode指定为MODE_PRIVATE,则该配置文件只能被自己的应用程序访问。
mode指定为MODE_WORLD_READABLE,则该配置文件除了自己访问外还可以被其它应该程序读取。
mode指定为MODE_WORLD_WRITEABLE,则该配置文件除了自己访问外还可以被其它应该程序读取和写入

二、PreferenceManager的方法getSharedPreferences()

这个方法我们可以通过查看其源码:

  1. * Gets a SharedPreferences instance that preferences managed by this will
  2. * use.
  3. *
  4. * @return A SharedPreferences instance pointing to the file that contains
  5. *         the values of preferences that are managed by this.
  6. */
  7. public SharedPreferences getSharedPreferences() {
  8. if (mSharedPreferences == null) {
  9. mSharedPreferences = mContext.getSharedPreferences(mSharedPreferencesName,
  10. mSharedPreferencesMode);
  11. }
  12. return mSharedPreferences;
  13. }
  1. /**
  2. * Gets a SharedPreferences instance that preferences managed by this will
  3. * use.
  4. *
  5. * @return A SharedPreferences instance pointing to the file that contains
  6. *         the values of preferences that are managed by this.
  7. */
  8. public SharedPreferences getSharedPreferences() {
  9. if (mSharedPreferences == null) {
  10. mSharedPreferences = mContext.getSharedPreferences(mSharedPreferencesName,
  11. mSharedPreferencesMode);
  12. }
  13. return mSharedPreferences;
  14. }

这个方法是一个普通的方法,必须有PreferenceManager的实例调用才行,因此我们再按图索骥找找其构造方法。

  1. /**
  2. * This constructor should ONLY be used when getting default values from
  3. * an XML preference hierarchy.
  4. * <p>
  5. * The {@link PreferenceManager#PreferenceManager(Activity)}
  6. * should be used ANY time a preference will be displayed, since some preference
  7. * types need an Activity for managed queries.
  8. */
  9. private PreferenceManager(Context context) {
  10. init(context);
  11. }
  12. private void init(Context context) {
  13. mContext = context;
  14. setSharedPreferencesName(getDefaultSharedPreferencesName(context));
  15. }
  1. /**
  2. * This constructor should ONLY be used when getting default values from
  3. * an XML preference hierarchy.
  4. * <p>
  5. * The {@link PreferenceManager#PreferenceManager(Activity)}
  6. * should be used ANY time a preference will be displayed, since some preference
  7. * types need an Activity for managed queries.
  8. */
  9. private PreferenceManager(Context context) {
  10. init(context);
  11. }
  12. private void init(Context context) {
  13. mContext = context;
  14. setSharedPreferencesName(getDefaultSharedPreferencesName(context));
  15. }
  1. /**
  2. * Sets the name of the SharedPreferences file that preferences managed by this
  3. * will use.
  4. *
  5. * @param sharedPreferencesName The name of the SharedPreferences file.
  6. * @see Context#getSharedPreferences(String, int)
  7. */
  8. public void setSharedPreferencesName(String sharedPreferencesName) {
  9. mSharedPreferencesName = sharedPreferencesName;
  10. mSharedPreferences = null;
  11. }
  1. /**
  2. * Sets the name of the SharedPreferences file that preferences managed by this
  3. * will use.
  4. *
  5. * @param sharedPreferencesName The name of the SharedPreferences file.
  6. * @see Context#getSharedPreferences(String, int)
  7. */
  8. public void setSharedPreferencesName(String sharedPreferencesName) {
  9. mSharedPreferencesName = sharedPreferencesName;
  10. mSharedPreferences = null;
  11. }
  1. private static String getDefaultSharedPreferencesName(Context context) {
  2. return context.getPackageName() + "_preferences";
  3. }
  1. private static String getDefaultSharedPreferencesName(Context context) {
  2. return context.getPackageName() + "_preferences";
  3. }

由以上方法,我们可以知道,最终我们调用getSharedPreferences()方法得到的是一个名为”yourpackageName_preferences“的偏好。同时其mode为默认私有。

三、getDefaultSharedPreferences方法

  1. /**
  2. * Gets a SharedPreferences instance that points to the default file that is
  3. * used by the preference framework in the given context.
  4. *
  5. * @param context The context of the preferences whose values are wanted.
  6. * @return A SharedPreferences instance that can be used to retrieve and
  7. *         listen to values of the preferences.
  8. */
  9. public static SharedPreferences getDefaultSharedPreferences(Context context) {
  10. return context.getSharedPreferences(getDefaultSharedPreferencesName(context),
  11. getDefaultSharedPreferencesMode());
  12. }
  13. private static String getDefaultSharedPreferencesName(Context context) {
  14. return context.getPackageName() + "_preferences";
  15. }
  16. private static int getDefaultSharedPreferencesMode() {
  17. return Context.MODE_PRIVATE;
  18. }
  1. /**
  2. * Gets a SharedPreferences instance that points to the default file that is
  3. * used by the preference framework in the given context.
  4. *
  5. * @param context The context of the preferences whose values are wanted.
  6. * @return A SharedPreferences instance that can be used to retrieve and
  7. *         listen to values of the preferences.
  8. */
  9. public static SharedPreferences getDefaultSharedPreferences(Context context) {
  10. return context.getSharedPreferences(getDefaultSharedPreferencesName(context),
  11. getDefaultSharedPreferencesMode());
  12. }
  13. private static String getDefaultSharedPreferencesName(Context context) {
  14. return context.getPackageName() + "_preferences";
  15. }
  16. private static int getDefaultSharedPreferencesMode() {
  17. return Context.MODE_PRIVATE;
  18. }

这个方法是静态的,因此可以直接调用,同时它与我们调用getSharedPreferences()方法得到的返回值是一样的,只是调用的方式不同罢了。

四、SharedPreferences到底是什么

它是一个轻量级的存储类,特别适合用于保存软件配置参数。使用SharedPreferences保存数据,其背后是用xml文件存放数据,文件存放在/data/data/<package name>/shared_prefs目录下:

  1. SharedPreferences sharedPreferences = getSharedPreferences("TEST", Context.MODE_PRIVATE);
  2. Editor editor = sharedPreferences.edit();//获取编辑器
  3. editor.putString("name", "Yang");
  4. editor.putInt("sex", "boy");
  5. editor.commit();//提交修改
  1. SharedPreferences sharedPreferences = getSharedPreferences("TEST", Context.MODE_PRIVATE);
  2. Editor editor = sharedPreferences.edit();//获取编辑器
  3. editor.putString("name", "Yang");
  4. editor.putInt("sex", "boy");
  5. editor.commit();//提交修改

生成的TEST.xml文件内容如下:

  1. <?xml version='1.0' encoding='utf-8' standalone='yes' ?>
  2. <map>
  3. <string name="name">Yang</string>
  4. <int name="sex">boy</string>
  5. </map>
  1. <?xml version='1.0' encoding='utf-8' standalone='yes' ?>
  2. <map>
  3. <string name="name">Yang</string>
  4. <int name="sex">boy</string>
  5. </map>

因为SharedPreferences背后是使用xml文件保存数据,getSharedPreferences(name,mode)方法的第一个参
数用于指定该文件的名称,名称不用带后缀,后缀会由Android自动加上。方法的第二个参数指定文件的操作模式,共有四种操作模式,这四种模式前面介绍
使用文件方式保存数据时已经讲解过。如果希望SharedPreferences背后使用的xml文件能被其他应用读和写,可以指定
Context.MODE_WORLD_READABLE和Context.MODE_WORLD_WRITEABLE权限。
另外Activity还提供了另一个getPreferences(mode)方法操作SharedPreferences,这个方法默认使用当前类不带包名的类名作为文件的名称。

如果访问其他应用中的Preference,前提条件是:该preference创建时指定了Context.MODE_WORLD_READABLE或者Context.MODE_WORLD_WRITEABLE权限。如:有个<package
name>为cn.yang.action的应用使用下面语句创建了preference。
getSharedPreferences("TEST", Context.MODE_WORLD_READABLE);
其他应用要访问上面应用的preference,首先需要创建上面应用的Context,然后通过Context 访问preference ,访问preference时会在应用所在包下的shared_prefs目录找到preference :
Context otherAppsContext = createPackageContext("cn.yang.action", Context.CONTEXT_IGNORE_SECURITY);
SharedPreferences sharedPreferences = otherAppsContext.getSharedPreferences("TEST", Context.MODE_WORLD_READABLE);
String name = sharedPreferences.getString("name", "");
int age = sharedPreferences.getInt("sex", "");

如果不通过创建Context访问其他应用的preference,也可以以读取xml文件方式直接访问其他应用preference对应的xml文件,如: 
File xmlFile = new File(“/data/data/<package name>/shared_prefs/itcast.xml”);//<package name>应替换成应用的包名。

getSharedPreferences()与getSharedPreferences()与getDefaultSharedPreferences()的区别的更多相关文章

  1. Android数据持久化技术 — — —SharedPreferences

    SharedPreferences是使用键值对的方式来存储数据. 要想使用SharedPreferences来存储数据,必须获取SharedPreferences对象,获取SharedPreferen ...

  2. Android Studio 学习(四) 数据库

    文件存储 写数据 String data = "Data ti save"; FileOutputStream out =null; BufferedWriter writer = ...

  3. 支持不同Android设备,包括:不同尺寸屏幕、不同屏幕密度、不同系统设置

    Some of the important variations that you should consider include different languages, screen sizes, ...

  4. Android四大组件全然解析(一)---Activity

    本文參考\android\android\frameworks\base\core\java\android\app\Activity.java文件里的类凝视.以及android/frameworks ...

  5. 使用fragmenttabhost后,子fragment怎么获取ID?怎么用getSharedPreferences

    使用fragmenttabhost后,子fragment怎么获取ID?怎么用getSharedPreferences public View onCreateView(LayoutInflater i ...

  6. android SharedPreferences apply和commit的区别

    1.apply没有返回值而commit返回boolean表明修改是否提交成功2.apply是将修改数据原子提交到内存, 而后异步真正提交到硬件磁盘, 而commit是同步的提交到硬件磁盘3.apply ...

  7. android 获取sharedpreference的三种方法的区别

    1. public SharedPreferences getPreferences (int mode) 通过Activity对象获取,获取的是本Activity私有的Preference,保存在系 ...

  8. Android中@id与@+id区别

    Android中的组件需要用一个int类型的值来表示,这个值也就是组件标签中的id属性值. id属性只能接受资源类型的值,也就是必须以@开头的值,例如,@id/abc.@+id/xyz等. 如果在@后 ...

  9. Android中@id与@+id区别和sharedUserId属性详解

    Android中的组件需要用一个int类型的值来表示,这个值也就是组件标签中的id属性值. id属性只能接受资源类型的值,也就是必须以@开头的值,例如,@id/abc.@+id/xyz等. 如果在@后 ...

随机推荐

  1. BZOJ3522: [Poi2014]Hotel

    3522: [Poi2014]Hotel Time Limit: 20 Sec  Memory Limit: 128 MBSubmit: 195  Solved: 85[Submit][Status] ...

  2. 清理ms sql server 大日志文件数据

    1.手动分离数据库: 2.手动删除日志文件: 3.重新生成日志文件: CREATE DATABASE FMIS0 ON (FILENAME = 'E:\FMIS0_DATA\FMIS0-Date') ...

  3. 【转】iOS Provisioning Profile(Certificate)与Code Signing详解 -- 待看

    原文网址:http://blog.sina.com.cn/s/blog_82c8198f0102vy4j.html 引言 关于开发证书配置(Certificates & Identifiers ...

  4. android webview js交互 第一节 (java和js交互)

    转载请注明出处         挺帅的移动开发专栏  http://blog.csdn.net/wangtingshuai/article/details/8631835        在androi ...

  5. asp.net Post Get提交数据转Model实例

    转自:http://blog.csdn.net/daodaowolf/article/details/8990694 此功能是将客户端HTTP协议POST GET方式提交的数据转换为某个Model实例 ...

  6. zoj 3620 Escape Time II

    http://acm.zju.edu.cn/onlinejudge/showProblem.do?problemId=4744 Escape Time II Time Limit: 2 Seconds ...

  7. HTML页面规范

    <!DOCTYPE HTML> <html> <head> <meta charset="UTF-8"> <title> ...

  8. 2D游戏编程5—锁定频率

    核心利用win心跳函数GetTickCount利用差量锁定fps,如下代码锁定30fps,缺点为如果计算机不能以30fps运行,程序将低于30fps #define WIN32_LEAN_AND_ME ...

  9. MSW下wxWidgets的安装与编译

    教程摘自网上各大博客.贴吧.论坛,结合自己的实践做了一些实质性的修改. 一.安装 首先从http://sourceforge.net/projects/wxwindows/files/2.8.12/w ...

  10. WE-1202 (JGX-X5 v1.3)刷openwrt

    当前固件版本显示 固件版本 RippleOS硬件型号 RippleTek WE-1202CPU型号是 MT7620N路由主板上面丝印是 JGX-X5  v1.3 买的时候选择的RippleOS固件,后 ...