Android面试题-SharedPreferences源码分析

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源码分析
    原文地址: https://blog.csdn.net/mwq384807683/article/details/72734873
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞