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

如果你熟悉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. }
 /**
* Gets a SharedPreferences instance that preferences managed by this will
* use.
*
* @return A SharedPreferences instance pointing to the file that contains
*         the values of preferences that are managed by this.
*/
public SharedPreferences getSharedPreferences() {
if (mSharedPreferences == null) {
mSharedPreferences = mContext.getSharedPreferences(mSharedPreferencesName,
mSharedPreferencesMode);
}
return mSharedPreferences;
}

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

[java] view plain copy print ?
  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. }
 /**
* This constructor should ONLY be used when getting default values from
* an XML preference hierarchy.
* <p>
* The {@link PreferenceManager#PreferenceManager(Activity)}
* should be used ANY time a preference will be displayed, since some preference
* types need an Activity for managed queries.
*/
private PreferenceManager(Context context) {
init(context);
}
private void init(Context context) {
mContext = context;
setSharedPreferencesName(getDefaultSharedPreferencesName(context));
}
[java] view plain copy print ?
  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. }
/**
* Sets the name of the SharedPreferences file that preferences managed by this
* will use.
*
* @param sharedPreferencesName The name of the SharedPreferences file.
* @see Context#getSharedPreferences(String, int)
*/
public void setSharedPreferencesName(String sharedPreferencesName) {
mSharedPreferencesName = sharedPreferencesName;
mSharedPreferences = null;
}
[java] view plain copy print ?
  1. private static String getDefaultSharedPreferencesName(Context context) {
  2. return context.getPackageName() + "_preferences";
  3. }
 private static String getDefaultSharedPreferencesName(Context context) {
return context.getPackageName() + "_preferences";
}

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

三、getDefaultSharedPreferences方法

[java] view plain copy print ?
  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. }
 /**
* Gets a SharedPreferences instance that points to the default file that is
* used by the preference framework in the given context.
*
* @param context The context of the preferences whose values are wanted.
* @return A SharedPreferences instance that can be used to retrieve and
*         listen to values of the preferences.
*/
public static SharedPreferences getDefaultSharedPreferences(Context context) {
return context.getSharedPreferences(getDefaultSharedPreferencesName(context),
getDefaultSharedPreferencesMode());
}
private static String getDefaultSharedPreferencesName(Context context) {
return context.getPackageName() + "_preferences";
}
private static int getDefaultSharedPreferencesMode() {
return Context.MODE_PRIVATE;
}

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

四、SharedPreferences到底是什么

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

[java] view plain copy print ?
  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();//提交修改
SharedPreferences sharedPreferences = getSharedPreferences("TEST", Context.MODE_PRIVATE);
Editor editor = sharedPreferences.edit();//获取编辑器
editor.putString("name", "Yang");
editor.putInt("sex", "boy");
editor.commit();//提交修改

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

[html] view plain copy print ?
  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>
<?xml version='1.0' encoding='utf-8' standalone='yes' ?>
<map>
<string name="name">Yang</string>
<int name="sex">boy</string>
</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. 安卓getSharedPreferences 与 getPreferences 与getDefaultSharedPreferences的区别

    整理了一下getSharedPreferences 与 getPreferences与getDefaultSharedPreferences的区别,有需要的朋友可以参考下. 1.SharedPrefe ...

  2. getSharedPreferences 与 getPreferences 与getDefaultSharedPreferences的区别

    1.SharedPreferences简介 为了保存软件的设置参数,Android 平台为我们提供了一个SharedPreferences 类,它是一个轻量级的存储类,特别适合用于保存软件配置参数.使 ...

  3. Android之getSharedPreferences与getDefaultSharedPreferences的区别

    SharedPreferences是一个轻量级的存储类,特别适合用于保存软件配置参数.使用SharedPreferences保存数据,其背后是用xml文件存放数据,文件存放在/data/data//s ...

  4. 转载:BP(反向传播算法)公式推导及例题解析

    首发于 深度学习与我的那些事 写文章 BP(反向传播算法)公式推导及例题解析 WILL 深度学习搬砖者 ​ 关注他 297 人 赞同了该文章 写在前面:最近赶上<模式识别>课程考试,就把B ...

  5. Android的5种数据存储方式概述

    Android有5种数据存储方式,具体分类如下: 1.应用内数据存储方式,程序外不可访问:SharedPreferences存储 应用场景:存储应用配置信息和常用信息. 获取SharedPrefere ...

  6. Android SharedPreferences 使用方法详解

    目录 1. SharedPreferences 定义介绍 2. SharedPreferences.Editor 方法介绍 2.1 apply() 2.2 commit() 2.3 clear() 2 ...

  7. Android四大组件完全解析(一)---Activity

    本文参考\android\android\frameworks\base\core\java\android\app\Activity.java文件中的类注释,以及android/frameworks ...

  8. SharedPreferences源码浅析

    0.6.0网盘地址 https://yunpan.cn/cBV9PmkBEPdcd (提取码:61a8) 我已经将Android 6.0 的源代码压缩上传到了360网盘,有需要的同学请自取. 1. 前 ...

  9. Android开发中Activity与Service之间getSharedPreferences不同步的解决方法

    当Activity中修改了shared的值,而Service中读到的还是原来的值,相当的头大.不过终于还是在网上找到了解决的办法. 向Google致敬,远离Baidu更健康,下面说正事. 我们在写程序 ...

最新文章

  1. Android 使用OpenCV的三种方式(Android Studio)
  2. 利用Servlet实现用户永久登录
  3. 快速排序(过程图解 参考啊哈算法)
  4. JSON模式在构建和部署API中的作用
  5. 【UVA 10816】 Travel in Desert (最小瓶颈树+最短路)
  6. 8080:The Tomcat connector configured to listen on port 8080 failed to start 的解决办法
  7. oracle 解死锁权限,讲解Oracle数据库中结束死锁进程的一般方法
  8. 一文弄懂什么是Istio
  9. [VSCode] 编辑 markdown 推荐插件
  10. slice,substr,substring三者的区别
  11. 使用表单传递参数,request处理参数出现未将对象引用设置到对象的实例
  12. 强烈推荐asp.net数据访问的官方指南系列 (Data Access Tutorials)
  13. 1302数码管c语言程序,基于AVR单片机的DS1302数码管时间显示C语言程序设计
  14. js 根据公历日期 算出农历_JS简单获取当前日期和农历日期的方法
  15. 算法竞赛入门【码蹄集新手村600题】(MT1101-1150)
  16. c语言atan,C语言atan()函数:求正切值为 x 的弧度数
  17. 360奇酷手机显示Log
  18. [转贴]比《同居密友》更搞笑的【阿奴与唐玉】陶海风格
  19. 爬取网页文本数据--Python
  20. 土壤水分传感器与介电常数的区别

热门文章

  1. 故障--桥接网卡的坑
  2. mysql 删除重复_MySQL查询和删除重复记录
  3. Linux中mysql的重启
  4. Unity数据可视化 温度图效果(一)
  5. 互融云区块链溯源防伪系统开发,超高并发,全程追溯
  6. 圣诞节装饰元素高清背景图素材
  7. 小程序疑难杂症破解(一)
  8. JetBrains产品字体大小调整
  9. FPM五:拆解前面的四——OVP做查询和结果
  10. mysql dataType