概述
SharedPreferences sp = context.getSharedPreferences(spName,
Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sp.edit();
editor.putString(key, (String) object);
editor.commit();
源码分析
@Override
public SharedPreferences getSharedPreferences(String name, int mode) {
SharedPreferencesImpl sp;
synchronized (ContextImpl.class) {
if (sSharedPrefs == null) {
sSharedPrefs = new ArrayMap<String, ArrayMap<String, SharedPreferencesImpl>>();
}
final String packageName = getPackageName();
ArrayMap<String, SharedPreferencesImpl> packagePrefs = sSharedPrefs.get(packageName);
if (packagePrefs == null) {
packagePrefs = new ArrayMap<String, SharedPreferencesImpl>();
sSharedPrefs.put(packageName, packagePrefs);
}
// 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";
}
}
sp = packagePrefs.get(name);
if (sp == null) {
File prefsFile = getSharedPrefsFile(name);
sp = new SharedPreferencesImpl(prefsFile, mode);
packagePrefs.put(name, sp);
return sp;
}
}
if ((mode & Context.MODE_MULTI_PROCESS) != 0 ||
getApplicationInfo().targetSdkVersion < android.os.Build.VERSION_CODES.HONEYCOMB) {
// If somebody else (some other process) changed the prefs
// file behind our back, we reload it.
This has been the
// historical (if undocumented) behavior.
sp.startReloadIfChangedUnexpectedly();
}
return sp;
}
源码可知
1) sSharedPrefs是一个静态的ArrayMap,表示一个包可以对应有一组SharedPreferences,并且直接映射文件名到SharedpreferencesImpl
sSharedPrefs = new ArrayMap<String, ArrayMap<String, SharedPreferencesImpl>>();
最后
以上就是欢呼墨镜为你收集整理的Android面试题-SharedPreferences源码分析的全部内容,希望文章能够帮你解决Android面试题-SharedPreferences源码分析所遇到的程序开发问题。
如果觉得靠谱客网站的内容还不错,欢迎将靠谱客网站推荐给程序员好友。
本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
发表评论 取消回复