SharePreferences源碼分析

最近在項目中使用了SharePreferences,因此看了一下SharePreferences相關的源碼,在此進行一下記錄

SharePreferences在Android提供的幾種數據存儲方式中屬於輕量級的鍵值存儲方式,以XML文件方式保存數據,通常用來存儲一些用戶行爲開關狀態等,一般的存儲一些常見的數據類型。

SharePreferences保存的xml文件存放於 /data/data/應用程序包/shared_prefs 的目錄下

SharePreferences是接口,位於android.content包中

SharePreferencesImpl是對於SharePreferences的實現,位於android.app包下

以下是一段SharePreferences的寫入以及讀取的例子:

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        SharedPreferences sp = getSharedPreferences("data", MODE_PRIVATE);
        SharedPreferences.Editor editor = sp.edit();
        editor.putString("name", "username");
        editor.commit();

        String s = sp.getString("name", "");
    }

第6行調用了ContextWrapper中的getSharedPreferences方法:

    @Override
    public SharedPreferences getSharedPreferences(String name, int mode) {
        return mBase.getSharedPreferences(name, mode);
    }

這裏調用了mBase的getSharedPreferences,mBase是ContextWrapper持有的Context變量,很明顯實際類型即是ContextImpl(Context的實現類):

    @Override
    public SharedPreferences getSharedPreferences(File file, int mode) {
        checkMode(mode);
        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;
    }

上面代碼首先檢查了是否緩存過對應的SharedPreferences,如果沒有緩存則創建SharedPreferencesImpl對象(第9行):

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

簡單說一下這裏的幾個變量:

  • mFile:當前的xml文件,即/data/data/應用程序包/shared_prefs/xxx.xml
  • mBackupFile:當前xml備份文件,名爲xxx.xml.bak
  • mMode:int類型,表示打開的模式
  • mLoaded:boolean類型,表示是否已經加載xml文件
  • mMap:xml的數據再內存中的儲存形式
在SharedPreferencesImpl構造函數中,調用了startLoadFromDisk方法加載xml中的數據:

    private void startLoadFromDisk() {
        synchronized (this) {
            mLoaded = false;
        }
        new Thread("SharedPreferencesImpl-load") {
            public void run() {
                synchronized (SharedPreferencesImpl.this) {
                    loadFromDiskLocked();
                }
            }
        }.start();
    }
	
    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();
    }

在startLoadFromDisk方法中,SharedPreferencesImpl開啓了新的子線程,並持有對象鎖來調用loadFromDiskLocked方法,通過XmlUtils工具類把xml讀取爲內存中的Map形式,最後通過notifyAll通知所有wait的地方

看完SharedPreferencesImpl的初始化,我們來看一下它的get方法,以例子中的getString爲例:

    public String getString(String key, String defValue) {
        synchronized (this) {
            awaitLoadedLocked();
            String v = (String)mMap.get(key);
            return v != null ? v : defValue;
        }
    }
	
    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 {
                wait();
            } catch (InterruptedException unused) {
            }
        }
    }

該方法在持有對象鎖的情況下,通過awaitLoadedLocked方法檢查是否已經從xml加載到內存map中,然後直接讀取map中的數據即可

awaitLoadedLocked方法處理了一些與StrictMode相關的問題,在此不做討論,在它發現SharedPreferencesImpl還沒有加載完畢時,會調用wait方法把當前線程掛起,直到加載完畢通過notifyAll喚醒

看完了SharedPreferencesImpl的get方法,我們再來看一下如何向其中插入新的數據:

    public Editor edit() {
        // TODO: remove the need to call awaitLoadedLocked() when
        // requesting an editor.  will require some work on the
        // Editor, but then we should be able to do:
        //
        //      context.getSharedPreferences(..).edit().putString(..).apply()
        //
        // ... all without blocking.
        synchronized (this) {
            awaitLoadedLocked();
        }

        return new EditorImpl();
    }

當我們調用edit方法時,會返回一個新的Edit接口的實現類EditorImpl,EditorImpl使用的是默認構造函數,它包含了兩個成員變量:

  • mModified:Map類型,用於存儲修改的鍵值對
  • mClear:boolean類型,用於標識是否清空SharedPreferences

獲取EditorImpl實例後,我們會調用其put或者clear方法修改SharedPreferences:

        public Editor putString(String key, String value) {
            synchronized (this) {
                mModified.put(key, value);
                return this;
            }
        }
		
        public Editor clear() {
            synchronized (this) {
                mClear = true;
                return this;
            }
        }

put方法會把我們的修改存入mModified變量,而clear方法會把mClear變量置爲true

當我們修改SharedPreferences完成後,會調用Editor的apply或者commit方法(apply爲異步提交,commit爲同步提交):

        public void apply() {
            final MemoryCommitResult mcr = commitToMemory();
            final Runnable awaitCommit = new Runnable() {
                    public void run() {
                        try {
                            mcr.writtenToDiskLatch.await();
                        } catch (InterruptedException ignored) {
                        }
                    }
                };

            QueuedWork.add(awaitCommit);

            Runnable postWriteRunnable = new Runnable() {
                    public void run() {
                        awaitCommit.run();
                        QueuedWork.remove(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() {
            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;
        }

兩個方法都首先調用了commitToMemory方法,把修改同步到內存中,然後都把寫入文件中的任務加入到了隊列當中等待執行

寫入文件的任務使用的同步工具是CounDownLatch,commit在當前線程調用了await方法等待寫入完成並返回Boolean表示寫入狀態,而apply在把寫入任務加入隊列後則返回了

在看commitToMemory方法之前,我們先來看看他的返回結果:MemoryCommitResult類

    // Return value from EditorImpl#commitToMemory()
    private static class MemoryCommitResult {
        public boolean changesMade;  // any keys different?
        public List<String> keysModified;  // may be null
        public Set<OnSharedPreferenceChangeListener> listeners;  // may be null
        public Map<?, ?> mapToWriteToDisk;
        public final CountDownLatch writtenToDiskLatch = new CountDownLatch(1);
        public volatile boolean writeToDiskResult = false;

        public void setDiskWriteResult(boolean result) {
            writeToDiskResult = result;
            writtenToDiskLatch.countDown();
        }
    }

MemoryCommitResult中:writeToDiskResult用於表示寫入文件的結果,mapToWriteToDisk表示寫入文件的map,即Editor更新後的map

commitToMemory方法如下:

        // Returns true if any changes were made
        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;
        }

在第26行我們可以看到,Editor首先通過mClear變量決定是否清空mMap,然後通過mModified變量決定如何修改mMap
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章