SharedPreferences原理分析

前言
想要實現(xiàn)簡單數(shù)據(jù)的持久化,我們首先會想到的方法肯定是SharedPreferences,有沒有思考過這個我們使用了很久的類有什么缺點。
getSharedPreferences的實現(xiàn)是在ContextImpl里面。
源碼分析:
getSharedPreferences(packageName, MODE_PRIVATE) => getSharedPreferencesPath(name) =>getSharedPreferences(file, mode)
其實getSharedPreferences的源碼很簡單,通過getSharedPreferencesPath返回一個File,由源碼可知,SharedPreferences內部存儲使用的是xml文件。

public File getSharedPreferencesPath(String name) {
        return makeFilename(getPreferencesDir(), name + ".xml");
    }
public SharedPreferences getSharedPreferences(File file, int mode) {
        SharedPreferencesImpl sp;
        synchronized (ContextImpl.class) {
            final ArrayMap<File, SharedPreferencesImpl> cache = getSharedPreferencesCacheLocked();
            sp = cache.get(file);
            if (sp == null) {
                checkMode(mode);
                if (getApplicationInfo().targetSdkVersion >= android.os.Build.VERSION_CODES.O) {
                    if (isCredentialProtectedStorage()
                            && !getSystemService(UserManager.class)
                                    .isUserUnlockingOrUnlocked(UserHandle.myUserId())) {
                        throw new IllegalStateException("SharedPreferences in credential encrypted "
                                + "storage are not available until after user is unlocked");
                    }
                }
                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;
    }

我們根據(jù)文件首先去緩存(ArrayMap)里面找,如果沒有找到,那么就創(chuàng)建SharedPreferencesImpl對象。
在SharedPreferencesImpl的構造方法中,會調用startLoadFromDisk()方法。然后通過BufferedInputStream去操作文件。

private void startLoadFromDisk() {
        synchronized (mLock) {
            mLoaded = false;
        }
        new Thread("SharedPreferencesImpl-load") {
            public void run() {
                loadFromDisk();
            }
        }.start();
    }
private void loadFromDisk() {
        ...
        Map<String, Object> map = null;
        StructStat stat = null;
        Throwable thrown = null;
        try {
            stat = Os.stat(mFile.getPath());
            if (mFile.canRead()) {
                BufferedInputStream str = null;
                try {
                    str = new BufferedInputStream(
                            new FileInputStream(mFile), 16 * 1024);
                    map = (Map<String, Object>) XmlUtils.readMapXml(str);
                } catch (Exception e) {
                    Log.w(TAG, "Cannot read " + mFile.getAbsolutePath(), e);
                } finally {
                    IoUtils.closeQuietly(str);
                }
            }
        } catch (ErrnoException e) {
            // An errno exception means the stat failed. Treat as empty/non-existing by
            // ignoring.
        } catch (Throwable t) {
            thrown = t;
        }

        ...
    }

接下來我們分析SharedPreferences的存儲數(shù)據(jù)的源碼。
我們以getString方法為例,其實就是從map中取出對應的值。這個map的值就是在loadFromDisk()方法中通過讀取file得到的。當然如果是空的話就會創(chuàng)建一個HashMap。

public String getString(String key, @Nullable String defValue) {
        synchronized (mLock) {
            awaitLoadedLocked();
            String v = (String)mMap.get(key);
            return v != null ? v : defValue;
        }
    }

下面我們分析put的流程。

mEditor = mSharedPreferences.edit()
mEditor.putInt(random.nextInt().toString(), random.nextInt()).commit()
 public Editor edit() {
        synchronized (mLock) {
            awaitLoadedLocked();
        }

        return new EditorImpl();
    }
public Editor putInt(String key, int value) {
            synchronized (mEditorLock) {
                mModified.put(key, value);
                return this;
            }
        }
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;
            }
            notifyListeners(mcr);
            return mcr.writeToDiskResult;
        }
public void apply() {
            final long startTime = System.currentTimeMillis();

            final MemoryCommitResult mcr = commitToMemory();
            final Runnable awaitCommit = new Runnable() {
                    @Override
                    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() {
                    @Override
                    public void run() {
                        awaitCommit.run();
                        QueuedWork.removeFinisher(awaitCommit);
                    }
                };

            SharedPreferencesImpl.this.enqueueDiskWrite(mcr, postWriteRunnable);
            notifyListeners(mcr);
        }
private void enqueueDiskWrite(final MemoryCommitResult mcr,
                                  final Runnable postWriteRunnable) {
        final boolean isFromSyncCommit = (postWriteRunnable == null);

        final Runnable writeToDiskRunnable = new Runnable() {
                @Override
                public void run() {
                    synchronized (mWritingToDiskLock) {
                        writeToFile(mcr, isFromSyncCommit);
                    }
                    synchronized (mLock) {
                        mDiskWritesInFlight--;
                    }
                    if (postWriteRunnable != null) {
                        postWriteRunnable.run();
                    }
                }
            };
        if (isFromSyncCommit) {
            boolean wasEmpty = false;
            synchronized (mLock) {
                wasEmpty = mDiskWritesInFlight == 1;
            }
            if (wasEmpty) {
                writeToDiskRunnable.run();
                return;
            }
        }

        QueuedWork.queue(writeToDiskRunnable, !isFromSyncCommit);
    }

edit()方法會創(chuàng)建一個EditorImpl對象,所以我們不應該在循環(huán)中調用edit()方法。
EditorImpl是SharedPreferencesImpl中的一個內部類。putInt()方法實際上就是將值存儲到EditorImpl中的HashMap中。
最后調用commit()方法進行提交。這里我們注意commitToMemory()和enqueueDiskWrite(mcr, null )這兩個方法。源碼我就不貼了,有興趣的可以自己去看看。
commitToMemory()方法作用是將需要寫入文件的數(shù)據(jù)存儲到一個map中即mapToWriteToDisk。
enqueueDiskWrite()方法會新建一個線程調用writeToFile()方法將上一步中的map數(shù)據(jù)通過FileOutputStream寫入到xml文件中。
apply()方法我們稍后分析。

apply()是否會造成ANR?

答案是肯定的,我們都知道apply()方法采用的是異步,使用線程進行提交,那么為什么會造成ANR。
在apply()方法中我們會新建一個任務進行數(shù)據(jù)的保存,然后調用 QueuedWork.queue(writeToDiskRunnable, !isFromSyncCommit)加入隊列。
我們都知道創(chuàng)建Activity時會在ActivityThread中調用handlePauseActivity方法。
在handlePauseActivity()方法中有一個QueuedWork.waitToFinish()等待隊列完成。所以,當任務所需時間過長時,這時候我們跳轉Activity的時候,依舊會造成ANR。

最后編輯于
?著作權歸作者所有,轉載或內容合作請聯(lián)系作者
【社區(qū)內容提示】社區(qū)部分內容疑似由AI輔助生成,瀏覽時請結合常識與多方信息審慎甄別。
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發(fā)布,文章內容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務。

相關閱讀更多精彩內容

友情鏈接更多精彩內容