打開
一般我們使用 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í)候到底是如何處理的呢,我們接著看最后寫入磁盤的過程
寫入的方法有兩種蒲肋, commit 和 apply 兩種蘑拯,兩種實(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é)束