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>();
            }

            final String packageName = getPackageName();
            ArrayMap packagePrefs = sSharedPrefs.get(packageName);
            if (packagePrefs == null) {
                packagePrefs = new ArrayMap();
                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>>();

你可能感兴趣的:(面试题)