Android源码分析之SharedPreferences

来源:互联网 发布:java部分中文乱码 编辑:程序博客网 时间:2024/06/05 06:19

在Android的日常开发中,相信大家都用过SharedPreferences来保存用户的某些settings值。Shared Preferences

以键值对的形式存储私有的原生类型数据,这里的私有的是指只对你自己的app可见的,也就是说别的app是无法访问到的。

客户端代码为了使用它有2种方式,一种是通过Context#getSharedPreferences(String prefName, int mode)方法,

另一种是Activity自己的getPreferences(int mode)方法,其内部还是调用了前者只是用activity的类名做了prefName而已,

我们先来看下Conext#getSharedPreferences的内部实现。其具体实现在ContextImpl.java文件中,代码如下:

复制代码
    @Override    public SharedPreferences getSharedPreferences(String name, int mode) {        SharedPreferencesImpl sp; // 这个是我们接下来要分析的重点类        synchronized (ContextImpl.class) {            if (sSharedPrefs == null) { // sSharedPrefs是一个静态的ArrayMap,注意这个类型,表示一个包可以对应有一组SharedPreferences                sSharedPrefs = new ArrayMap<String, ArrayMap<String, SharedPreferencesImpl>>();            } // ArrayMap<String, SharedPreferencesImpl>表示文件名到SharedpreferencesImpl的映射关系            final String packageName = getPackageName(); // 先通过包名找到与之关联的prefs集合packagePrefs            ArrayMap<String, SharedPreferencesImpl> packagePrefs = sSharedPrefs.get(packageName);            if (packagePrefs == null) { // lazy initialize                packagePrefs = new ArrayMap<String, SharedPreferencesImpl>();                sSharedPrefs.put(packageName, packagePrefs); // 添加到全局sSharedPrefs中            }            // 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"; // name传null时候的特殊处理,用"null"代替                }            }            sp = packagePrefs.get(name); // 再找与文件名name关联的sp对象;            if (sp == null) {            // 如果还没有,                File prefsFile = getSharedPrefsFile(name); // 则先根据name构建一个prefsFile对象                sp = new SharedPreferencesImpl(prefsFile, mode); // 再new一个SharedPreferencesImpl对象的实例                packagePrefs.put(name, sp); // 并添加到packagePrefs中
return sp; // 第一次直接return } }
// 如果不是第一次,则在Android3.0之前或者mode设置成了MULTI_PROCESS的话,调用reload
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; // 最后返回SharedPreferences的具体对象sp }
复制代码

通过分析这段代码我们大体能得到2个重要结论:

1. 静态的ArrayMap变量sSharedPrefs,因为它一直伴随我们的app存在,所以如果你的SharedPreferences很多的话,map会很大,

从而会占用较大部分内存;一般来说,你可以将多个小的prefs文件合并到一个稍大的里面。

2. 当你用SharedPreferences来跨进程通信的时候,你会发现你不能像往常(非MODE_MULTI_PROCESS的情况)那样,调用一次

getSharedPreferences方法然后用这个实例来读取值。因为如果你不是每次调用getSharedPreferences方法的话,此方法最后的那段

reload代码不会被执行,那么可能别的进程写的最新数据在你的进程里面还是看不到(本人项目亲历)。而且reload虽然不在UI线程中操

作但毕竟也是耗时(费力)的IO操作,所以Android doc关于Context.MODE_MULTI_PROCESS字段的说明中也明确提及有更好的跨进

程通信方式。

  看SharedPreferences的源码我们知道它只是一个接口而已,在其内部又有2个嵌套的接口:OnSharedPreferenceChangeListener

和Editor;前者代表了回调接口,表示当一个shared preference改变时如果你感兴趣则有能力收听到通知;Editor则定义了用来写值的

接口,而用来读数据的方法都在大的SharedPreferences接口中定义。它们的具体实现在SharedPreferencesImpl.java文件中。

  下面就让我们睁大眼睛,好好研究下这个类具体是怎么实现的。和以往一样,我们还是从关键字段和ctor开始,源码如下:

复制代码
    // Lock ordering rules: // 这3行注释明确写明了加锁的顺序,注意下;在我们自己的代码里如果遇到类似    //  - acquire SharedPreferencesImpl.this before EditorImpl.this // (需要多把锁)的情况,则最好也写清楚,    //  - acquire mWritingToDiskLock before EditorImpl.this         // 这是个很好的习惯,方便别人看你的代码。    private final File mFile; // 我们的shared preferences背后存储在这个文件里    private final File mBackupFile; // 与mFile对应的备份文件    private final int mMode; // 如MODE_PRIVATE,MODE_WORLD_READABLE,MODE_WORLD_WRITEABLE,MODE_MULTI_PROCESS等    private Map<String, Object> mMap;     // guarded by 'this' 将settings缓存在内存中的map    private int mDiskWritesInFlight = 0;  // guarded by 'this' 表示还未写到disk中的写操作的数目    private boolean mLoaded = false;      // guarded by 'this' 表示settings整个从disk加载到内存map中完毕的标志    private long mStatTimestamp;          // guarded by 'this' 文件的最近一次更新时间    private long mStatSize;               // guarded by 'this' 文件的size,注意这些字段都被this对象保护    private final Object mWritingToDiskLock = new Object(); // 写操作的锁对象
复制代码

接着我们看看其构造器:

复制代码
    SharedPreferencesImpl(File file, int mode) {        mFile = file;        mBackupFile = makeBackupFile(file); // 根据file,产生一个.bak的File对象        mMode = mode;        mLoaded = false;        mMap = null;        startLoadFromDisk();    }
复制代码

构造器也比较简单,主要做2件事情,初始化重要变量&将文件异步加载到内存中。

  下面我们紧接着看下将settings文件异步加载到内存中的操作:

复制代码
    private void startLoadFromDisk() {        synchronized (this) {            mLoaded = false; // 开始load前,将其reset(加锁),后面的loadFromDiskLocked方法会检测这个标记        }        new Thread("SharedPreferencesImpl-load") {            public void run() {                synchronized (SharedPreferencesImpl.this) {                    loadFromDiskLocked(); // 在一个新的线程中开始load,注意锁加在SharedPreferencesImpl对象上,                }                         // 也就是说这时候如果其他线程调用SharedPreferences.getXXX之类的方法都会被阻塞。            }        }.start();    }    private void loadFromDiskLocked() { // 此方法受SharedPreferencesImpl.this锁的保护        if (mLoaded) { // 如果已加载完毕则直接返回            return;        }        if (mBackupFile.exists()) {            mFile.delete(); // 如果备份文件存在,则删除(非备份)文件mFile,            mBackupFile.renameTo(mFile); // 将备份文件重命名为mFile(相当于mFile现在又存在了只是内容其实已经变成了mBackupFile而已)        }                                // 或者说接下来的读操作实际是从备份文件中来的        // 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 = Libcore.os.stat(mFile.getPath()); // 得到文件的一系列信息,有linux c经验的同学应该都很眼熟            if (mFile.canRead()) { // 前提是文件可读啊。。。一般都是成立的,否则我们最终会得到一个空的map                BufferedInputStream str = null;                try {                    str = new BufferedInputStream(                            new FileInputStream(mFile), 16*1024);                    map = XmlUtils.readMapXml(str); // 用str中所有xml信息构造一个map返回                } catch (XmlPullParserException e) {                    Log.w(TAG, "getSharedPreferences", e);                } catch (FileNotFoundException e) {                    Log.w(TAG, "getSharedPreferences", e);                } catch (IOException e) {                    Log.w(TAG, "getSharedPreferences", e);                } finally {                    IoUtils.closeQuietly(str);                }            }        } catch (ErrnoException e) {        }        mLoaded = true; // 标记加载过了        if (map != null) {            mMap = map; // 如果map非空,则设置mMap,并更新文件访问时间、文件大小字段            mStatTimestamp = stat.st_mtime;            mStatSize = stat.st_size;        } else {            mMap = new HashMap<String, Object>(); // 否则初始化一个empty的map        }        notifyAll(); // 最后通知所有阻塞在SharedPreferencesImpl.this对象上的线程数据ready了,可以往下进行了    }
复制代码

   接下来我们看看将文件reload进内存的方法:

复制代码
    void startReloadIfChangedUnexpectedly() {        synchronized (this) { // 也是在SharedPreferencesImpl.this对象上加锁            // TODO: wait for any pending writes to disk?            if (!hasFileChangedUnexpectedly()) { // 如果没有我们之外的意外更改,则直接返回,因为我们的数据                return;                          // 仍然是最新的,没必要reload            }            startLoadFromDisk(); // 真正需要reload        }    }    // Has the file changed out from under us?  i.e. writes that    // we didn't instigate.    private boolean hasFileChangedUnexpectedly() { // 这个方法检测是否别的进程也修改了文件        synchronized (this) {            if (mDiskWritesInFlight > 0) { // 知道是我们自己引起的,则直接返回false,表示是预期的                // If we know we caused it, it's not unexpected.                if (DEBUG) Log.d(TAG, "disk write in flight, not unexpected.");                return false;            }        }        final StructStat stat;        try {            /*             * Metadata operations don't usually count as a block guard             * violation, but we explicitly want this one.             */            BlockGuard.getThreadPolicy().onReadFromDisk();            stat = Libcore.os.stat(mFile.getPath());        } catch (ErrnoException e) {            return true;        }        synchronized (this) { // 比较文件的最近更新时间和size是否和我们手头的一样,如果不一样则说明有unexpected修改            return mStatTimestamp != stat.st_mtime || mStatSize != stat.st_size;        }    }
复制代码

  接下来要分析的是一堆读操作相关的,各种getXXX,它们做的事情本质都是一样的,不一个个分析了,只说下大体思想:在同步块中

等待加载完成,然后直接从mMap中返回需要的信息,而不是每次都触发一次读文件操作(本人没看源码之前一直以为是读文件操作),

这里我们只看下block等待的方法:

复制代码
    private void awaitLoadedLocked() { // 注意此方法也是在SharedPreferencesImpl.this锁的保护下        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) { // 当条件变量不成立时(即没load完成)则无限等待            try {          // 注意这个经典的形式我们已经见到好几次了(上一次是在HandlerThread中,还记得?)                wait();            } catch (InterruptedException unused) {            }        }    }
复制代码

  接下来我们看看真正修改(写)文件的操作是怎么实现的,代码如下:

复制代码
    // Return value from EditorImpl#commitToMemory()    private static class MemoryCommitResult { // 此静态类表示EditorImpl#commitToMemory()的返回值        public boolean changesMade;  // any keys different?        public List<String> keysModified;  // may be null        public Set<OnSharedPreferenceChangeListener> listeners;  // may be null        public Map<?, ?> mapToWriteToDisk; // 要写到disk中的map(持有数据的map)        public final CountDownLatch writtenToDiskLatch = new CountDownLatch(1); // 初始化为1的count down闭锁        public volatile boolean writeToDiskResult = false;        public void setDiskWriteResult(boolean result) { // 结束写操作的时候调用,result为true表示成功            writeToDiskResult = result;            writtenToDiskLatch.countDown(); // 此调用会释放所有block在await调用上的线程        }    }    public final class EditorImpl implements Editor { // Editor的具体实现类        private final Map<String, Object> mModified = Maps.newHashMap(); // 持有所有要修改的数据即调用putXXX方法时提供的参数        private boolean mClear = false;        public Editor putString(String key, String value) {            synchronized (this) { // EditorImpl.this锁用来保护mModified对象                mModified.put(key, value); // 修改不是立即写到文件中的,而是暂时放在内存的map中的                return this; // 返回当前对象,以便支持链式方法调用            }        }        public Editor putStringSet(String key, Set<String> values) {            synchronized (this) {                mModified.put(key,                        (values == null) ? null : new HashSet<String>(values));                return this;            }        }        public Editor putInt(String key, int value) {            synchronized (this) {                mModified.put(key, value);                return this;            }        }        public Editor putLong(String key, long value) {            synchronized (this) {                mModified.put(key, value);                return this;            }        }        public Editor putFloat(String key, float value) {            synchronized (this) {                mModified.put(key, value);                return this;            }        }        public Editor putBoolean(String key, boolean value) {            synchronized (this) {                mModified.put(key, value);                return this;            }        }        public Editor remove(String key) {            synchronized (this) {                mModified.put(key, this); // 注意remove操作比较特殊,remove一个key时会put一个特殊的this对象,                return this;              // 后面的commitToMemory方法对此有特殊处理            }        }        public Editor clear() {            synchronized (this) {                mClear = true;                return this;            }        }        public void apply() {            final MemoryCommitResult mcr = commitToMemory();            final Runnable awaitCommit = new Runnable() {                    public void run() {                        try {                            mcr.writtenToDiskLatch.await(); // block等待写操作完成                        } catch (InterruptedException ignored) {                        }                    }                };            QueuedWork.add(awaitCommit); // 将awaitCommit添加到QueueWork中;这里顺带引出一个疑问:那么apply方法到底
// 会不会导致SharedPreferences丢失数据更新呢?(有兴趣的同学可以看看QueuedWork#waitToFinish方法都在哪里,
// 什么情况下被调用了就明白了)
Runnable postWriteRunnable
= new Runnable() { // 写操作完成之后要执行的runnable public void run() { awaitCommit.run(); // 执行awaitCommit runnable并从QueueWork中移除 QueuedWork.remove(awaitCommit); } }; SharedPreferencesImpl.this.enqueueDiskWrite(mcr, postWriteRunnable); // 准备将mcr写到磁盘中 // 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); } // Returns true if any changes were made private MemoryCommitResult commitToMemory() { // 当此方法调用时,这里有2级锁,先是SharedPreferencesImpl.this锁, MemoryCommitResult mcr = new MemoryCommitResult(); // 然后是EditorImpl.this锁,所以当commit的时候任何调用getXXX synchronized (SharedPreferencesImpl.this) {// 的方法都会block。此方法的目的主要是构造一个合适的MemoryCommitResult对象。 // We optimistically don't make a deep copy until // // a memory commit comes in when we're already // writing to disk. if (mDiskWritesInFlight > 0) { // We can't modify our mMap as a currently // in-flight write owns it. Clone it before // modifying it. // noinspection unchecked mMap = new HashMap<String, Object>(mMap); // 当有多个写操作等待执行时make a copy of mMap } mcr.mapToWriteToDisk = mMap; mDiskWritesInFlight++; // 表示又多了一个(未完成的)写操作 boolean hasListeners = mListeners.size() > 0; if (hasListeners) { mcr.keysModified = new ArrayList<String>(); mcr.listeners = new HashSet<OnSharedPreferenceChangeListener>(mListeners.keySet()); } synchronized (this) { // 加锁在EditorImpl对象上 if (mClear) { // 处理clear的情况 if (!mMap.isEmpty()) { mcr.changesMade = true; mMap.clear(); } mClear = false; // reset } // 注意这里由于先处理了clear操作,所以clear并不会清掉本次写操作的数据,只会clear掉以前有的数据 for (Map.Entry<String, Object> e : mModified.entrySet()) { // 遍历mModified处理各个key、value String k = e.getKey(); Object v = e.getValue(); if (v == this) { // magic value for a removal mutation // 这个就是标记为删除的特殊value if (!mMap.containsKey(k)) { continue; } mMap.remove(k); // 从mMap中删除 } else { boolean isSame = false; if (mMap.containsKey(k)) { Object existingValue = mMap.get(k); if (existingValue != null && existingValue.equals(v)) { continue; } } mMap.put(k, v); // 将mModified中的值更新到mMap中 } mcr.changesMade = true; // 走到这步表示有更新产生 if (hasListeners) { mcr.keysModified.add(k); } } mModified.clear(); // 一次commit执行完后清空mModified,准备接下来的put操作 } } return mcr; } public boolean commit() { MemoryCommitResult mcr = commitToMemory(); SharedPreferencesImpl.this.enqueueDiskWrite( // 发起写操作 mcr, null /* sync write on this thread okay */); try { // block等待写操作完成,如果是UI线程可能会造成UI卡顿,所以Android建议我们如果不关心返回值可以考虑用apply替代 mcr.writtenToDiskLatch.await(); } catch (InterruptedException e) { return false; } notifyListeners(mcr); return mcr.writeToDiskResult; } private void notifyListeners(final MemoryCommitResult mcr) { // 注意此方法中callback调用永远发生在UI线程中 if (mcr.listeners == null || mcr.keysModified == null || mcr.keysModified.size() == 0) { return; } if (Looper.myLooper() == Looper.getMainLooper()) { for (int i = mcr.keysModified.size() - 1; i >= 0; i--) { final String key = mcr.keysModified.get(i); for (OnSharedPreferenceChangeListener listener : mcr.listeners) { if (listener != null) { listener.onSharedPreferenceChanged(SharedPreferencesImpl.this, key); } } } } else { // Run this function on the main thread. ActivityThread.sMainThreadHandler.post(new Runnable() { public void run() { notifyListeners(mcr); } }); } } }
复制代码

  最后我们看下SharedPreferencesImpl的最后3个重要方法(也即真正写操作发生的地方):

复制代码
    /**     * 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, // 此方法的doc写的很详细,你可以仔细阅读下                                  final Runnable postWriteRunnable) {        final Runnable writeToDiskRunnable = new Runnable() { // 真正写操作的runnable                public void run() {                    synchronized (mWritingToDiskLock) { // 第3把锁,保护写操作的                        writeToFile(mcr);                    }                    synchronized (SharedPreferencesImpl.this) {                        mDiskWritesInFlight--; // 表示1个写操作完成了,少了1个in flight的了                    }                    if (postWriteRunnable != null) {                        postWriteRunnable.run(); // 如果非空则执行之(apply的时候满足)                    }                }            };        final boolean isFromSyncCommit = (postWriteRunnable == null); // 判断我们是否从commit方法来的        // Typical #commit() path with fewer allocations, doing a write on        // the current thread.        if (isFromSyncCommit) {            boolean wasEmpty = false;            synchronized (SharedPreferencesImpl.this) {                wasEmpty = mDiskWritesInFlight == 1; // 如果mDiskWritesInFlight是1的话表示有1个写操作需要执行            }            if (wasEmpty) { // 在UI线程中直接调用其run方法执行之                writeToDiskRunnable.run();                return; // 执行完毕后返回            }        }        // 否则来自apply调用的话,直接扔一个writeToDiskRunnable给单线程的thread executor去执行        QueuedWork.singleThreadExecutor().execute(writeToDiskRunnable);    }    // 依据file创建与之对应的文件(在文件系统中)    private static FileOutputStream createFileOutputStream(File file) {        FileOutputStream str = null;        try {            str = new FileOutputStream(file);        } catch (FileNotFoundException e) {            File parent = file.getParentFile();            if (!parent.mkdir()) {                Log.e(TAG, "Couldn't create directory for SharedPreferences file " + file);                return null;            }            FileUtils.setPermissions(                parent.getPath(),                FileUtils.S_IRWXU|FileUtils.S_IRWXG|FileUtils.S_IXOTH,                -1, -1);            try {                str = new FileOutputStream(file);            } catch (FileNotFoundException e2) {                Log.e(TAG, "Couldn't create SharedPreferences file " + file, e2);            }        }        return str;    }    // Note: must hold mWritingToDiskLock    private void writeToFile(MemoryCommitResult mcr) {        // Rename the current file so it may be used as a backup during the next read        if (mFile.exists()) { // 如果对应的mFile存在的话,针对于非第一次操作            if (!mcr.changesMade) {                // If the file already exists, but no changes were                // made to the underlying map, it's wasteful to                // re-write the file.  Return as if we wrote it                // out.                mcr.setDiskWriteResult(true); // 没有什么改动发生调用此方法结束,因为没啥可写的                return;            }            if (!mBackupFile.exists()) { // 如果没备份文件存在的话,尝试将mFile重命名为mBackupFile
// 因为如果本次写操作失败的话(可能这时数据已经不完整了或破坏掉了),下次再读的话还可以从备份文件中恢复
if (!mFile.renameTo(mBackupFile)) { // 如果重命名失败则调用mcr.setDiskWriteResult(false)结束 Log.e(TAG, "Couldn't rename file " + mFile + " to backup file " + mBackupFile); mcr.setDiskWriteResult(false); return; } } else { // 备份文件存在的话,则删除mFile(因为接下来我们马上要重新写一个新mFile了) mFile.delete(); } } // Attempt to write the file, delete the backup and return true as atomically as // possible. If any exception occurs, delete the new file; next time we will restore // from the backup. try { FileOutputStream str = createFileOutputStream(mFile); // 尝试创建mFile if (str == null) { // 如果失败则调用mcr.setDiskWriteResult(false)收场 mcr.setDiskWriteResult(false); return; } XmlUtils.writeMapXml(mcr.mapToWriteToDisk, str); // 将mcr的mapToWriteToDisk全部写到str对应的文件中 FileUtils.sync(str); // 将buffer中的数据都flush到底层设备中 str.close(); // 关闭文件流 ContextImpl.setFilePermissionsFromMode(mFile.getPath(), mMode, 0); // 设置文件权限根据mMode try { final StructStat stat = Libcore.os.stat(mFile.getPath()); synchronized (this) { mStatTimestamp = stat.st_mtime; // 同步更新文件相关的2个变量 mStatSize = stat.st_size; } } catch (ErrnoException e) { // Do nothing } // Writing was successful, delete the backup file if there is one. mBackupFile.delete(); // 删除备份文件,标记写操作成功完成,返回 mcr.setDiskWriteResult(true); return; } catch (XmlPullParserException e) { Log.w(TAG, "writeToFile: Got exception:", e); } catch (IOException e) { Log.w(TAG, "writeToFile: Got exception:", e); } // Clean up an unsuccessfully written file if (mFile.exists()) { // 如果以上写操作出了任何异常则删掉(内容)不完整的mFile;放心因为开始写之前我们已经备份了,哈哈 if (!mFile.delete()) { Log.e(TAG, "Couldn't clean up partially-written file " + mFile); } } mcr.setDiskWriteResult(false); // 标记写操作以失败告终 }
复制代码

到现在我们算是明白了mMode和文件权限的关系,为了更清晰直观的展现,最后附上ContextImpl.setFilePermissionsFromMode的源码:

复制代码
    static void setFilePermissionsFromMode(String name, int mode,            int extraPermissions) {        int perms = FileUtils.S_IRUSR|FileUtils.S_IWUSR // 我们可以看出默认创建的文件权限是user自己可读可写,            |FileUtils.S_IRGRP|FileUtils.S_IWGRP // 同组可读可写            |extraPermissions; // 和其他附加的,一般给0表示没附加的权限        if ((mode&MODE_WORLD_READABLE) != 0) { // 接下来我们看到只有MODE_WORLD_READABLE/MODE_WORLD_WRITEABLE有用            perms |= FileUtils.S_IROTH; // other可读        }        if ((mode&MODE_WORLD_WRITEABLE) != 0) {            perms |= FileUtils.S_IWOTH; // other可写        }        if (DEBUG) {            Log.i(TAG, "File " + name + ": mode=0x" + Integer.toHexString(mode)                  + ", perms=0x" + Integer.toHexString(perms));        }        FileUtils.setPermissions(name, perms, -1, -1);    }
复制代码

  通过以上分析我们可以看出每次调用commit()、apply()都会将整个settings全部写到文件中,即使你只改动了一个setting。因为它是

基于全局的,而不是增量的,所以你的客户端代码中一定不要出现一个putXXX就紧跟着一个commit/apply,而是put完所有你要的改动,

最后调用一次commit/apply即可。至此Android提供的持久化primitive数据的机制SharedPreferences就已经完全分析完毕了。

0 0
原创粉丝点击