SharedPreferences介绍
SharedPreferences是Android官方的Key-Value键值对形式的轻量级存储方式,能够存储少量的数据,支持基本类型、字符串类型。
文件存储路径是/data/data/应用程序包名/shared_prefs
。
SharedPreferences使用
1、创建SharedPreferences
SharedPreferences getSharedPreferences(String name, @PreferencesMode int mode);
参数1:SharedPreferences
文件名称。
参数2:
Context.MODE_PRIVATE
:表示数据只能被本应用程序读、写。
Context.MODE_WORLD_READABLE
:表示数据能被其他应用程序读,但不能写。
Context.MODE_WORLD_WRITEABLE
: 表示数据能被其他应用程序读,写。
Context.MODE_MULTI_PROCESS
:跨进程。
2、使用Editor
// 创建SP对象
SharedPreferences sp = context.getSharedPreferences("config", Context.MODE_PRIVATE);
// 创建Editor对象
SharedPreferences.Editor edit = sp.edit();
// 使用Editor存储数据
edit.putInt(key, value);
// 使用Editor同步提交数据
edit.commit();
SharedPreferences.Editor的方法:
public interface Editor {
// 存储数据
Editor putString(String key, @Nullable String value);
Editor putStringSet(String key, @Nullable Set<String> values);
Editor putInt(String key, int value);
Editor putLong(String key, long value);
Editor putFloat(String key, float value);
Editor putBoolean(String key, boolean value);
// 删除SharedPreferences中指定key对应的数据项
Editor remove(String key);
// 清空SharedPreferences里所有数据
Editor clear();
// 当Editor编辑完成后,使用该方法同步提交修改
boolean commit();
// 当Editor编辑完成后,使用该方法异步提交修改
void apply();
}
getSharedPreferences过程
使用SharedPreferences
的时候是从上下文context.getSharedPreferences获取的,所以直接从Context类中找到该接口:
public abstract SharedPreferences getSharedPreferences(String name, @PreferencesMode int mode);
发现只是抽象接口,所以再从实现类ContextImpl
中找到该方法的实现:
getSharedPreferences(String name, int mode)
方法
@Override
public SharedPreferences getSharedPreferences(String name, int mode) {
if (mPackageInfo.getApplicationInfo().targetSdkVersion <
Build.VERSION_CODES.KITKAT) {
if (name == null) {
name = "null";
}
}
File file;
// 添加同步锁
synchronized (ContextImpl.class) {
if (mSharedPrefsPaths == null) {
// 创建Map存储sp的文件
mSharedPrefsPaths = new ArrayMap<>();
}
file = mSharedPrefsPaths.get(name);
if (file == null) {
// 获取sp的存储文件
file = getSharedPreferencesPath(name);
// 缓存到map中
mSharedPrefsPaths.put(name, file);
}
}
return getSharedPreferences(file, mode);
}
getSharedPreferencess(File file, int mode)
方法
@Override
public SharedPreferences getSharedPreferences(File file, int mode) {
SharedPreferencesImpl sp;
//添加同步锁
synchronized (ContextImpl.class) {
final ArrayMap<File, SharedPreferencesImpl> cache = getSharedPreferencesCacheLocked();
//从缓存中获取SharedPreferencesImpl对象
sp = cache.get(file);
if (sp == null) {
checkMode(mode);
// 如果不存在则创建SharedPreferencesImpl对象
sp = new SharedPreferencesImpl(file, mode);
cache.put(file, sp);
return sp;
}
}
// 提供了 MODE_MULTI_PROCESS 这个 Flag 来支持跨进程
if ((mode & Context.MODE_MULTI_PROCESS) != 0