Android SharedPreferences 源码分析

2,470 阅读8分钟

SharedPreferences(下称SP)在平时开发应用比较多。我应用SP主要用于保存一些影响业务的数值,比如是否第一次激活应用,第一次激活的时间,ABTest分组标志等等。在开发的应用中,很多与统计数据相关的数值都是用SP进行存储管理的,使用过程中的确因为理解不深,出现问题,影响产品决策。因此准确理解使用SP很重要。

本文参照Android-26的源码,分析SP的原理和需要注意的问题,主要包括以下几部分:

  • 分析实现SP功能的类及相互关系
  • SP的内容的读取、写入
  • 需要注意的问题

SP的主要类及关系:

SP的功能实现的主要接口和类有:SharedPreferences,Editor,SharedPreferencesImpl,EditorImpl以及ContextImpl,它们之间的关系下图(UML现学现卖,欢迎指出问题):


接口SharedPreferences定义了SP提供SP文件的读操作,其包含子接口EditorImpl定义了对SP文件写相关的操作。SharedPreferencesImpl类实现SharedPreferences接口,具体实现SP文件的读功能以及为保证读准确而提供的线程安全等条件,其内部类EditorImpl实现了Editor接口,负责SP文件的实际写操作。ContextImpl类包含SharedPreferencesImpl,通过方法getSharedPreferences()对外提供SP实例供开发者使用。

SP内容的读写:

  • 获取SP实例
     @Override
    public SharedPreferences getSharedPreferences(File file, int mode) {
        //检查读写模式
        checkMode(mode);
        //文件级别加密检查?(待进一步研究)
        if (getApplicationInfo().targetSdkVersion >= android.os.Build.VERSION_CODES.O) {
            if (isCredentialProtectedStorage()
                    && !getSystemService(StorageManager.class).isUserKeyUnlocked(
                            UserHandle.myUserId())
                    && !isBuggy()) {
                throw new IllegalStateException("SharedPreferences in credential encrypted "
                        + "storage are not available until after user is unlocked");
            }
        }
        SharedPreferencesImpl sp;
        synchronized (ContextImpl.class) {
            final ArrayMap<File, SharedPreferencesImpl> cache = getSharedPreferencesCacheLocked();
            sp = cache.get(file);
            if (sp == null) {
                sp = new SharedPreferencesImpl(file, mode);
                cache.put(file, 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;
    }

首先通过checkMode()方法检查文件的读写模式,然后针对Android O 及以上版本,进行文件加密检查,这些检查都没有问题后,从缓存中获取或者创建新的SP实例并返回。先看一下checkMode方法的实现:

 private void checkMode(int mode) {
        if (getApplicationInfo().targetSdkVersion >= Build.VERSION_CODES.N) {
            if ((mode & MODE_WORLD_READABLE) != 0) {
                throw new SecurityException("MODE_WORLD_READABLE no longer supported");
            }
            if ((mode & MODE_WORLD_WRITEABLE) != 0) {
                throw new SecurityException("MODE_WORLD_WRITEABLE no longer supported");
            }
        }
    }

为安全考虑,Android在N及以上彻底禁止MODE_WORLD_READABLE和MODE_WORLD_WRITEABLE模式,checkMode方法中具体做了限制。

synchronized (ContextImpl.class) {
            final ArrayMap<File, SharedPreferencesImpl> cache = getSharedPreferencesCacheLocked();
            sp = cache.get(file);
            if (sp == null) {
                sp = new SharedPreferencesImpl(file, mode);
                cache.put(file, sp);
                return sp;
            }
        }

这段代码是从缓存中根据指定的File获取SP实例,getSharedPreferencesCacheLocked()方法的实现如下:

  private ArrayMap<File, SharedPreferencesImpl> getSharedPreferencesCacheLocked() {
        if (sSharedPrefsCache == null) {
            sSharedPrefsCache = new ArrayMap<>();
        }

        final String packageName = getPackageName();
        ArrayMap<File, SharedPreferencesImpl> packagePrefs = sSharedPrefsCache.get(packageName);
        if (packagePrefs == null) {
            packagePrefs = new ArrayMap<>();
            sSharedPrefsCache.put(packageName, packagePrefs);
        }

        return packagePrefs;
    }

静态变量sSharedPrefsCache的定义是一个Key为String类型,Value的ArrayMap<File, SharedPreferencesImpl>的ArrayMap:

 /**
     * Map from package name, to preference name, to cached preferences.
     */
private static ArrayMap<String, ArrayMap<File, SharedPreferencesImpl>> sSharedPrefsCache;

它以包名为key,将每个应用下的SP实例缓存在一个ArrayMap中。 其实整个获取SP实例的逻辑很简单:从缓存中查找,将查找到的对象直接返回,如果没有就调用SharedPreferencesImpl的构造方法,创建SP实例,添加到缓存中,并返回。

SP内容的读写:

先看一下SharedPreferencesImpl构造方法的实现:

 SharedPreferencesImpl(File file, int mode) {
        mFile = file;
        mBackupFile = makeBackupFile(file);
        mMode = mode;
        mLoaded = false;
        mMap = null;
        startLoadFromDisk();
    }

构造方法主要进行了建立备份文件实例,加载文件到内存的操作,在startLoadFromDisk()方法中,通过同步枷锁,启动线程将文件内容加入到内存,这里提供了一层线程安全保障:

private void startLoadFromDisk() {
        synchronized (mLock) {
            mLoaded = false;
        }
        new Thread("SharedPreferencesImpl-load") {
            public void run() {
                loadFromDisk();
            }
        }.start();
    }

具体负责文件内容加载的loadFromDisk()方法:

rivate void loadFromDisk() {
        synchronized (mLock) {
            if (mLoaded) {
                return;
            }
            if (mBackupFile.exists()) {
                mFile.delete();
                mBackupFile.renameTo(mFile);
            }
        }

        // Debugging
        if (mFile.exists() && !mFile.canRead()) {
            Log.w(TAG, "Attempt to read preferences file " + mFile + " without permission");
        }

        Map map = null;
        StructStat stat = null;
        try {
            stat = Os.stat(mFile.getPath());
            if (mFile.canRead()) {
                BufferedInputStream str = null;
                try {
                    str = new BufferedInputStream(
                            new FileInputStream(mFile), 16*1024);
                    map = XmlUtils.readMapXml(str);
                } catch (Exception e) {
                    Log.w(TAG, "Cannot read " + mFile.getAbsolutePath(), e);
                } finally {
                    IoUtils.closeQuietly(str);
                }
            }
        } catch (ErrnoException e) {
            /* ignore */
        }

        synchronized (mLock) {
            mLoaded = true;
            if (map != null) {
                mMap = map;
                mStatTimestamp = stat.st_mtime;
                mStatSize = stat.st_size;
            } else {
                mMap = new HashMap<>();
            }
            mLock.notifyAll();
        }
    }

在这个方法中,首先是加锁判断当前状态,如果已经加载完成,就直接返回,否则会重新设置备份的文件对象。然后使用XmlUtils读取文件内容,并保存到Map对象mMap中,通知所有正在等待的客户,文件读取完成,可以进行键值对的读写操作了。这里需要注意:系统会一次性把SP文件内容读入到内存并保存在Map对象中。这就是SP文件内容的加载过程。

下面我们看看从SP文件中获取值的过程,以getInt()方法为例:

 public int getInt(String key, int defValue) {
        synchronized (mLock) {
            awaitLoadedLocked();
            Integer v = (Integer)mMap.get(key);
            return v != null ? v : defValue;
        }
    }

首先加锁,避免读取到错误的值,然后调用awaitLoadedLocked(),这个方法的作用是检测文件内容是否已经读取到mMap对象中,如果没有读取完成,就阻塞,直到接收到读取完成的通知之后,再从mMap对象中取出value,具体代码如下:

private void awaitLoadedLocked() {
        if (!mLoaded) {
            // Raise an explicit StrictMode onReadFromDisk for this
            // thread, since the real read will be in a different
            // thread and otherwise ignored by StrictMode.
            BlockGuard.getThreadPolicy().onReadFromDisk();
        }
        while (!mLoaded) {
            try {
                mLock.wait();
            } catch (InterruptedException unused) {
            }
        }
    }

可以看到,如果文件内容读取完成,getInt()方法会一直阻塞。如果不知道这个细节,很容易导致应用出现ANR的问题。比如场景:进程创建的时候,会进行很多的逻辑处理,在UI进程从SP中获取value时,如果文件读取时间长,UI进程被阻塞,容易发生ANR。另外由于系统是使用Map缓存SP文件中的键值对的,基本类型不能作为value传入,所以想读取基本类型的值时,要求传入一个defaultValue,考虑到运行的安全,避免出现的情况是,客户希望获取一个int值,API返回一个Null的囧像。

SP的写入操作是由EditorImpl具体实现的。对SP中键值对的读写操作,分两步,第一步是由EditorImpl直接更改mMap的值;第二步,将mMap中的键值对写入到文件中保存。这里需要重点关注两个方法:apply()和commit(),它们的实现如下:

 public void apply() {
            final long startTime = System.currentTimeMillis();
            //将改动吸入到内容内存
            final MemoryCommitResult mcr = commitToMemory();
            final Runnable awaitCommit = new Runnable() {
                    public void run() {
                        try {
                            mcr.writtenToDiskLatch.await();
                        } catch (InterruptedException ignored) {
                        }

                        if (DEBUG && mcr.wasWritten) {
                            Log.d(TAG, mFile.getName() + ":" + mcr.memoryStateGeneration
                                    + " applied after " + (System.currentTimeMillis() - startTime)
                                    + " ms");
                        }
                    }
                };

            QueuedWork.addFinisher(awaitCommit);
            Runnable postWriteRunnable = new Runnable() {
                    public void run() {
                        awaitCommit.run();
                        QueuedWork.removeFinisher(awaitCommit);
                    }
                };
            //改动已经提交到内存了,等待系统调度写入文件
            SharedPreferencesImpl.this.enqueueDiskWrite(mcr, postWriteRunnable);

            // Okay to notify the listeners before it's hit disk
            // because the listeners should always get the same
            // SharedPreferences instance back, which has the
            // changes reflected in memory.
            notifyListeners(mcr);
        }
public boolean commit() {
            long startTime = 0;

            if (DEBUG) {
                startTime = System.currentTimeMillis();
            }

            MemoryCommitResult mcr = commitToMemory();

            SharedPreferencesImpl.this.enqueueDiskWrite(
                mcr, null /* sync write on this thread okay */);
            try {
                mcr.writtenToDiskLatch.await();
            } catch (InterruptedException e) {
                return false;
            } finally {
                if (DEBUG) {
                    Log.d(TAG, mFile.getName() + ":" + mcr.memoryStateGeneration
                            + " committed after " + (System.currentTimeMillis() - startTime)
                            + " ms");
                }
            }
            notifyListeners(mcr);
            return mcr.writeToDiskResult;
        }

这两个方法都做了两件事情,调用commitToMemory()及时将改动提交到对应的内存区域,然后提交一个写入文件的任务,等待系统调度。唯一不同的是,apply将文件写入操作放到一个Runnable对象中,等待系统在工作线程中调用。commit方法则是直接在主线程中进行写入操作。这一点可以从调度写入操作的enqueueDiskWrite()方法中看出:

  /**
     * Enqueue an already-committed-to-memory result to be written
     * to disk.
     *
     * They will be written to disk one-at-a-time in the order
     * that they're enqueued.
     *
     * @param postWriteRunnable if non-null, we're being called
     *   from apply() and this is the runnable to run after
     *   the write proceeds.  if null (from a regular commit()),
     *   then we're allowed to do this disk write on the main
     *   thread (which in addition to reducing allocations and
     *   creating a background thread, this has the advantage that
     *   we catch them in userdebug StrictMode reports to convert
     *   them where possible to apply() ...)
     */
    private void enqueueDiskWrite(final MemoryCommitResult mcr,
                                  final Runnable postWriteRunnable) {
        final boolean isFromSyncCommit = (postWriteRunnable == null);

        final Runnable writeToDiskRunnable = new Runnable() {
                public void run() {
                    synchronized (mWritingToDiskLock) {
                        writeToFile(mcr, isFromSyncCommit);
                    }
                    synchronized (mLock) {
                        mDiskWritesInFlight--;
                    }
                    //使用本次写入任务提供的Runnable对象
                    if (postWriteRunnable != null) {
                        postWriteRunnable.run();
                    }
                }
            };

        // Typical #commit() path with fewer allocations, doing a write on
        // the current thread.
        if (isFromSyncCommit) {
            boolean wasEmpty = false;
            synchronized (mLock) {
                wasEmpty = mDiskWritesInFlight == 1;
            }
            if (wasEmpty) {
                writeToDiskRunnable.run();
                return;
            }
        }

        QueuedWork.queue(writeToDiskRunnable, !isFromSyncCommit);
    }

如果在提交写入任务时,没有提供对应的调度Runnable对象,即此次调度任务是通过commit()方法提交,那么会在当前的线程中进写操作。这就是为什么提倡使用apply方法的原因。其实大家根本不需要关注apply和commit两个方法在数据一致性的差异,这两个方法对数据的操作都是一致的,唯一区别就是写入文件时一个另起线程,一个在当前线程。

需要注意的问题:

  • SP文件的读写是一次I/O操作,尽量避开设备资源紧张的场景操作。
  • getValue方法是线程阻塞的
  • apply方法对app性能的影响小,尽量使用apply方法。
  • 尽量链式调用 Editor对象,因为每次调用SharedPreferencesImpl对象的edit()方法都会创建新的Editor实例
  • 每个Editor实例包含一个map,包含该Editor实例操作的所有键值对。在调用apply或者commit方法之后会首先写到mMap中。因此,不调用提交方法,那么操作的键值对会被丢弃。