赞
踩
SharedPreferences作为Android常用的持久化组件,很常用,在系统设置应用中就大量地被使用。相信大家基本都是用过,但是在使用过程中,大家是否又知道它的实现原理呢?
SharedPreferences使用很简单,比如我们要它保存某个字符串,在Activity使用如下:
/**
* save number
* @param num
*/
private void saveNumber(String num) {
SharedPreferences sharedPreferences = getSharedPreferences("light_persist", MODE_PRIVATE);
sharedPreferences.edit().putString("number", num).apply();
//sharedPreferences.edit().putString("number", number).commit();
}
上面代码执行后,会将变量num保存在/data/data/应用包名/shared_prefs/light_persist.xml。SharedPreferences使用很简单,但这并不表示它本身也简单,下面从三个角度来深入了解SharedPreferences的实现原理
在上面的例子中,我们是在Activity通过调用getSharedPreferences()获取SharedPreferences对象,我们看下它的具体实现是怎样的。首先,我们要明白以下几点:
对于第一点,通过类的继承关系很容易知道;对于第二点,这个会涉及到Activity的启动过程,在ActivityThread的performLaunchActivity()方法中会初始化context,context初始化的时序图如下
Activity在启动的时候会创建ContextImpl对象,并调用Activity的attach()方法将ContextImpl对象传递下去,最终给ContextWrapper的Context对象mBase赋值。
在明白Activity中调用getSharedPreferences()方法实际上调用了CcontextImpl.getSharedPreferences()后,我们就很容易明白SharedPreferences对象是如何初始化的了。SharedPreferences对象初始化过程如下所示
下面我们就看下SharedPreference初始化的代码实现
@Override public SharedPreferences getSharedPreferences(String name, int mode) { // At least one application in the world actually passes in a null // name. This happened to work because when we generated the file name // we would stringify it to "null.xml". Nice. if (mPackageInfo.getApplicationInfo().targetSdkVersion < Build.VERSION_CODES.KITKAT) { if (name == null) { name = "null"; } } File file; synchronized (ContextImpl.class) { if (mSharedPrefsPaths == null) { mSharedPrefsPaths = new ArrayMap<>(); } file = mSharedPrefsPaths.get(name); //从缓存集合中取name对应的file,如果集合中没有,则根据name创建对应的file并添加进集合 if (file == null) { file = getSharedPreferencesPath(name); mSharedPrefsPaths.put(name, file); } } return getSharedPreferences(file, mode); }
@Override
public SharedPreferences getSharedPreferences(File file, int mode) {
SharedPreferencesImpl sp;
synchronized (ContextImpl.class) {
//getSharedPreferencesCacheLocked()根据应用包名从缓存集合中取ArrayMap集合
final ArrayMap<File, SharedPreferencesImpl> cache = getSharedPreferencesCacheLocked();
sp = cache.get(file);
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。