SharedPreferences源碼分析

打開

一般我們使用 SharedPreferences 都是直接或者間接調(diào)用 ContextImpl類的getSharedPreferences 方法,我們看一下這個(gè)方法的代碼

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

從源碼中可以看到私杜,首先設(shè)置了一些Map用來緩存數(shù)據(jù)贞滨,其次根據(jù)名稱獲取本地的文件浪汪,最后創(chuàng)建 SharedPreferencesImpl 類, SharedPreferencesImpl 類是 SharedPreferences 接口的具體實(shí)現(xiàn)。在 SharedPreferencesImpl 類的構(gòu)造方法中通過線程將文件讀取到內(nèi)存中儡循,具體代碼如下:

private void loadFromDiskLocked() {
    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 (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;
        mStatTimestamp = stat.st_mtime;
        mStatSize = stat.st_size;
    } else {
        mMap = new HashMap<String, Object>();
    }
    notifyAll();
}

首先 loadFromDiskLocked() 方法是在新創(chuàng)建的線程中執(zhí)行所以不用擔(dān)心阻塞主線程混滔,在方法開始的地方首先檢查上次數(shù)據(jù)保存是否異常洒疚,如果有異常則恢復(fù)異常發(fā)生之前的數(shù)據(jù)。然后通過 XmlUtils.readMapXml() 方法將文件中的數(shù)據(jù)讀取到一個(gè) HashMap 中坯屿,這里也可以看出數(shù)據(jù)在文件中是以xml格式存儲(chǔ)的

讀取

讀取數(shù)據(jù)比較簡(jiǎn)單通過 getBoolean() 可以簡(jiǎn)單看出數(shù)據(jù)讀取的流程

public boolean getBoolean(String key, boolean defValue) {
    synchronized (this) {
        awaitLoadedLocked();
        Boolean v = (Boolean)mMap.get(key);
        return v != null ? v : defValue;
    }
}

其中 awaitLoadedLocked() 等待數(shù)據(jù)從文件中讀取完畢油湖,然后將數(shù)據(jù)從Map中取出。

寫入

讓我們來看一下寫入的一般用法

SharedPreferences sp = getSharedPreferences(name, mode);
Editor editor = sp.edit();
editor.putBoolean(key, true);
editor.commit(); //editor.apply();

我們逐行來分析寫入的過程
第一行 getSharedPreferences() 在上面已經(jīng)分析過领跛,這里不再贅述
第二行通過 sp.edit() 獲取到一個(gè) Editor乏德,這里看一下具體實(shí)現(xiàn)

public Editor edit() {
    synchronized (this) {
        awaitLoadedLocked();
    }

    return new EditorImpl();
}

這里首先等待數(shù)據(jù)讀取完畢,然后創(chuàng)建一個(gè) EditorImpl 對(duì)象吠昭,其中EditorImpl是Editor的具體實(shí)現(xiàn)
第三行代碼通過 putBoolean() 方法將數(shù)據(jù)存儲(chǔ)到內(nèi)部的一個(gè)Map中喊括,其中比較有意思的是 remove(key)clear() 兩個(gè)方法

public Editor remove(String key) {
    synchronized (this) {
        mModified.put(key, this);
        return this;
    }
}

public Editor clear() {
    synchronized (this) {
        mClear = true;
        return this;
    }
}

clear 方法中設(shè)置了一個(gè)清除的標(biāo)記位,而在 remove 方法中就很有意思了矢棚,將Editor自身存儲(chǔ)到了Map中郑什,那么在數(shù)據(jù)寫入到文件中的時(shí)候到底是如何處理的呢,我們接著看最后寫入磁盤的過程
寫入的方法有兩種蒲肋, commitapply 兩種蘑拯,兩種實(shí)現(xiàn)有一些區(qū)別(廢話),先來看 commit 的實(shí)現(xiàn)

public boolean commit() {
    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;
}

commit()方法中做了三件事情兜粘,將數(shù)據(jù)從 Editor 中拷貝到 SharedPreferences 中(可以稱之為提交到內(nèi)存中)申窘,將數(shù)據(jù)寫入到文件中,通知監(jiān)聽器
首先看一下提交到內(nèi)存的過程

private MemoryCommitResult commitToMemory() {
    MemoryCommitResult mcr = new MemoryCommitResult();
    synchronized (SharedPreferencesImpl.this) {
        // 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);
        }
        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) {
            if (mClear) {
                if (!mMap.isEmpty()) {
                    mcr.changesMade = true;
                    mMap.clear();
                }
                mClear = false;
            }

            for (Map.Entry<String, Object> e : mModified.entrySet()) {
                String k = e.getKey();
                Object v = e.getValue();
                // "this" is the magic value for a removal mutation. In addition,
                // setting a value to "null" for a given key is specified to be
                // equivalent to calling remove on that key.
                if (v == this || v == null) {
                    if (!mMap.containsKey(k)) {
                        continue;
                    }
                    mMap.remove(k);
                } else {
                    if (mMap.containsKey(k)) {
                        Object existingValue = mMap.get(k);
                        if (existingValue != null && existingValue.equals(v)) {
                            continue;
                        }
                    }
                    mMap.put(k, v);
                }

                mcr.changesMade = true;
                if (hasListeners) {
                    mcr.keysModified.add(k);
                }
            }

            mModified.clear();
        }
    }
    return mcr;
}

首先檢查是否有數(shù)據(jù)正在寫入到磁盤中孔轴,如果有剃法,需要做一次深拷貝。接著檢查 mClear 標(biāo)志距糖,這個(gè)標(biāo)志是在調(diào)用 editor.clear() 的時(shí)候設(shè)置的玄窝,如果設(shè)置了就會(huì)將原來存儲(chǔ)在Map中的數(shù)據(jù)全部刪除。緊接著通過一個(gè)for循環(huán)悍引,遍歷Editor中Map的數(shù)據(jù)恩脂。首先檢查value是否是Editor本身(在調(diào)用 editor.remove() 的時(shí)候設(shè)置)或者為 null ,如果是趣斤,刪除SharedPreferences中Map對(duì)應(yīng)的數(shù)據(jù)俩块。否則就會(huì)將數(shù)據(jù)添加到Map中。遍歷完成后將原有Editor中的Map數(shù)據(jù)清空,至此完成了內(nèi)存數(shù)據(jù)的拷貝
下面看一下寫入到文件的過程

private void enqueueDiskWrite(final MemoryCommitResult mcr,
                                final Runnable postWriteRunnable) {
    final Runnable writeToDiskRunnable = new Runnable() {
            public void run() {
                synchronized (mWritingToDiskLock) {
                    writeToFile(mcr);
                }
                synchronized (SharedPreferencesImpl.this) {
                    mDiskWritesInFlight--;
                }
                if (postWriteRunnable != null) {
                    postWriteRunnable.run();
                }
            }
        };

    final boolean isFromSyncCommit = (postWriteRunnable == null);

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

    QueuedWork.singleThreadExecutor().execute(writeToDiskRunnable);
}

首先創(chuàng)建一個(gè) writeToDiskRunnable 玉凯,將具體的寫入邏輯封裝起來势腮。然后判斷是否調(diào)用的 commit() 方法,如果是漫仆,并且當(dāng)前只有一個(gè)寫入請(qǐng)求的話捎拯,就在當(dāng)前線程中執(zhí)行寫入操作,否則盲厌,將寫入操作添加到線程池中執(zhí)行
下面分析寫入操作的過程

private void writeToFile(MemoryCommitResult mcr) {
    // Rename the current file so it may be used as a backup during the next read
    if (mFile.exists()) {
        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()) {
            if (!mFile.renameTo(mBackupFile)) {
                Log.e(TAG, "Couldn't rename file " + mFile
                        + " to backup file " + mBackupFile);
                mcr.setDiskWriteResult(false);
                return;
            }
        } else {
            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);
        if (str == null) {
            mcr.setDiskWriteResult(false);
            return;
        }
        XmlUtils.writeMapXml(mcr.mapToWriteToDisk, str);
        FileUtils.sync(str);
        str.close();
        ContextImpl.setFilePermissionsFromMode(mFile.getPath(), mMode, 0);
        try {
            final StructStat stat = Os.stat(mFile.getPath());
            synchronized (this) {
                mStatTimestamp = stat.st_mtime;
                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()) {
        if (!mFile.delete()) {
            Log.e(TAG, "Couldn't clean up partially-written file " + mFile);
        }
    }
    mcr.setDiskWriteResult(false);
}

首先判斷本次提交是否有數(shù)據(jù)更改署照,如果沒有,則不需要寫入任何內(nèi)容吗浩,否則將保存著舊數(shù)據(jù)的文件備份起來建芙。然后通過 XmlUtils.writeMapXml()方法將數(shù)據(jù)寫入到文件中,并設(shè)置相應(yīng)的訪問權(quán)限懂扼。如果寫入成功禁荸,將備份文件刪除,至此一次 commit() 數(shù)據(jù)寫入操作結(jié)束

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
  • 序言:七十年代末阀湿,一起剝皮案震驚了整個(gè)濱河市赶熟,隨后出現(xiàn)的幾起案子,更是在濱河造成了極大的恐慌炕倘,老刑警劉巖钧大,帶你破解...
    沈念sama閱讀 219,490評(píng)論 6 508
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件,死亡現(xiàn)場(chǎng)離奇詭異罩旋,居然都是意外死亡啊央,警方通過查閱死者的電腦和手機(jī),發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 93,581評(píng)論 3 395
  • 文/潘曉璐 我一進(jìn)店門涨醋,熙熙樓的掌柜王于貴愁眉苦臉地迎上來瓜饥,“玉大人,你說我怎么就攤上這事浴骂∨彝粒” “怎么了?”我有些...
    開封第一講書人閱讀 165,830評(píng)論 0 356
  • 文/不壞的土叔 我叫張陵溯警,是天一觀的道長(zhǎng)趣苏。 經(jīng)常有香客問我,道長(zhǎng)梯轻,這世上最難降的妖魔是什么食磕? 我笑而不...
    開封第一講書人閱讀 58,957評(píng)論 1 295
  • 正文 為了忘掉前任,我火速辦了婚禮喳挑,結(jié)果婚禮上彬伦,老公的妹妹穿的比我還像新娘滔悉。我一直安慰自己,他們只是感情好单绑,可當(dāng)我...
    茶點(diǎn)故事閱讀 67,974評(píng)論 6 393
  • 文/花漫 我一把揭開白布回官。 她就那樣靜靜地躺著,像睡著了一般搂橙。 火紅的嫁衣襯著肌膚如雪歉提。 梳的紋絲不亂的頭發(fā)上,一...
    開封第一講書人閱讀 51,754評(píng)論 1 307
  • 那天区转,我揣著相機(jī)與錄音唯袄,去河邊找鬼。 笑死蜗帜,一個(gè)胖子當(dāng)著我的面吹牛,可吹牛的內(nèi)容都是我干的资厉。 我是一名探鬼主播厅缺,決...
    沈念sama閱讀 40,464評(píng)論 3 420
  • 文/蒼蘭香墨 我猛地睜開眼,長(zhǎng)吁一口氣:“原來是場(chǎng)噩夢(mèng)啊……” “哼宴偿!你這毒婦竟也來了湘捎?” 一聲冷哼從身側(cè)響起,我...
    開封第一講書人閱讀 39,357評(píng)論 0 276
  • 序言:老撾萬榮一對(duì)情侶失蹤窄刘,失蹤者是張志新(化名)和其女友劉穎窥妇,沒想到半個(gè)月后,有當(dāng)?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體娩践,經(jīng)...
    沈念sama閱讀 45,847評(píng)論 1 317
  • 正文 獨(dú)居荒郊野嶺守林人離奇死亡活翩,尸身上長(zhǎng)有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點(diǎn)故事閱讀 37,995評(píng)論 3 338
  • 正文 我和宋清朗相戀三年,在試婚紗的時(shí)候發(fā)現(xiàn)自己被綠了翻伺。 大學(xué)時(shí)的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片材泄。...
    茶點(diǎn)故事閱讀 40,137評(píng)論 1 351
  • 序言:一個(gè)原本活蹦亂跳的男人離奇死亡,死狀恐怖吨岭,靈堂內(nèi)的尸體忽然破棺而出拉宗,到底是詐尸還是另有隱情,我是刑警寧澤辣辫,帶...
    沈念sama閱讀 35,819評(píng)論 5 346
  • 正文 年R本政府宣布旦事,位于F島的核電站,受9級(jí)特大地震影響急灭,放射性物質(zhì)發(fā)生泄漏姐浮。R本人自食惡果不足惜,卻給世界環(huán)境...
    茶點(diǎn)故事閱讀 41,482評(píng)論 3 331
  • 文/蒙蒙 一化戳、第九天 我趴在偏房一處隱蔽的房頂上張望单料。 院中可真熱鬧埋凯,春花似錦、人聲如沸扫尖。這莊子的主人今日做“春日...
    開封第一講書人閱讀 32,023評(píng)論 0 22
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽换怖。三九已至甩恼,卻和暖如春,著一層夾襖步出監(jiān)牢的瞬間沉颂,已是汗流浹背条摸。 一陣腳步聲響...
    開封第一講書人閱讀 33,149評(píng)論 1 272
  • 我被黑心中介騙來泰國(guó)打工, 沒想到剛下飛機(jī)就差點(diǎn)兒被人妖公主榨干…… 1. 我叫王不留铸屉,地道東北人钉蒲。 一個(gè)月前我還...
    沈念sama閱讀 48,409評(píng)論 3 373
  • 正文 我出身青樓,卻偏偏與公主長(zhǎng)得像彻坛,于是被迫代替她去往敵國(guó)和親顷啼。 傳聞我的和親對(duì)象是個(gè)殘疾皇子,可洞房花燭夜當(dāng)晚...
    茶點(diǎn)故事閱讀 45,086評(píng)論 2 355

推薦閱讀更多精彩內(nèi)容