Using Shared Preferences 使用共享参数

一、SharedPreferences 的用途

我们可以用它来保存一些用户数据. 但是这些数据必须是原始类型的数据. 我们可以这样理解: 一个 Preferences 就是一个文件, 在这个 Preferences 中存储了多个 Preference, 而一个 Preference 就保存了用户的一个数据.

二、获取 SharedPreferences 对象

方法1:

public abstract SharedPreferences getSharedPreferences(String name, int mode);

方法2:

public SharedPreferences getPreferences(int mode) {
return getSharedPreferences(getLocalClassName(), mode);
}

三、SharedPreferences 的存储

  1. 使用 SharedPreferences 方式保存数据, 其实质是使用 XML 文件存储数据. 所以不需要指定文件后缀 .xml.

  2. 该文件是存放在 /data/data/<package name>/shared_prefs 目录下. 所以只要指定文件名即可, 而不需要指定路径.

四、操作

  1. 读取数据

  2. 写入数据

五、区别

getPreferences:
  /**
* Retrieve a SharedPreferences object for accessing preferences that are private to this activity.
* 获得一个 SharedPreferences 对象, 通过它来访问当前 Activity 私有的 preferences.
*
* This simply calls the underlying getSharedPreferences(String, int) method by passing in this activity's class name as the preferences name.
* 它只是简单的调用了底层的 getSharedPreferences(String, int) 方法, 并将当前 Activity 的简单类名做为 preferences 的名字传递进去.
*
*
@param mode Operating mode. Use MODE_PRIVATE for the default operation, MODE_WORLD_READABLE and MODE_WORLD_WRITEABLE to control permissions.
* mode 操作模式. MODE_PRIVATE 为默认的操作, MODE_WORLD_READABLE 和 MODE_WORLD_WRITEABLE 用于控制访问权限.
*
*
@return Returns the single SharedPreferences instance that can be used to retrieve and modify the preference values.
* 返回一个 SharedPreferences 实例, 用于检索和修改 preference 值.
*/
public SharedPreferences getPreferences(int mode) {
return getSharedPreferences(getLocalClassName(), mode);
}
  /**
* Returns class name for this activity with the package prefix removed.
* This is the default name used to read and write settings.
* 返回当前 Activiry 的类名(移除了包名前缀). 这是用于读写设置的默认名称.
*
*
@return The local class name. 返回本地类名
*/
public String getLocalClassName() {
final String pkg = getPackageName();
final String cls = mComponent.getClassName();
int packageLen = pkg.length();
if (!cls.startsWith(pkg) || cls.length() <= packageLen
|| cls.charAt(packageLen) != '.') {
return cls;
}
return cls.substring(packageLen+1);
}
getSharedPreferences:
  public abstract SharedPreferences getSharedPreferences(String name,int mode);
getDefaultSharedPreferences:
  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;
}
getDefaultSharedPreferences()方法默认的文件名为:当前应用的包名_preferences,文件模式为: Context.MODE_PRIVATE.
但提供了setSharedPreferencesMode(mode)方法设置文件操作模式;setSharedPreferencesName(name)来设置文件名称;




原文地址:https://www.cnblogs.com/xpxpxp2046/p/2423811.html