SharedPreference源碼分析
SharePreference屬于輕量級的鍵值存儲方式,以XML文件方式保存數據。
老規矩,先上圖:
SharedPreference.png
獲取SharedPreferences
我們一般有兩種方式獲取SharedPreference:
Activity的public SharedPreferences getPreferences(int mode)方法
或者
ContextImpl的public SharedPreferences getSharedPreferences(String name, int mode)方法
Activity的public SharedPreferences getPreferences(int mode)方法實際上調用了ContextImpl的public SharedPreferences getSharedPreferences(String name, int mode)方法:
public SharedPreferences getPreferences(int mode) {
return getSharedPreferences(getLocalClassName(), mode);
}
public abstract SharedPreferences getSharedPreferences(String name, int mode)是Context抽象類的抽象方法,它的實現類是哪個呢?這個涉及到Activity的啟動,感興趣的可以看下ActivityThread的performLaunchActivity方法。這個Context的實現類是ContextImpl類。
看下它的getSharedPreferences方法。
@Override
public SharedPreferences getSharedPreferences(String name, int mode) {
SharedPreferencesImpl sp;
synchronized (ContextImpl.class) {
if (sSharedPrefs == null) {
sSharedPrefs = new ArrayMap<String, ArrayMap<String, SharedPreferencesImpl>>(); //創建一個map,鍵是包名,值還是一個map(j鍵是傳入的name,值是SharedPreferencesImpl對象)
}
final String packageName = getPackageName();
ArrayMap<String, SharedPreferencesImpl> packagePrefs = sSharedPrefs.get(packageName); //獲取當前包名對應的map
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); //根據傳入的name獲取SharedPreferencesImpl對象
if (sp == null) { //若為空,則新建一個SharedPreferencesImpl對象
File prefsFile = getSharedPrefsFile(name); //使用name創建一個文件
sp = new SharedPreferencesImpl(prefsFile, mode); //新建一個SharedPreferencesImpl對象
packagePrefs.put(name, sp); //放入當前包名對應的map中
return sp; //方法SharedPreferencesImpl對象
}
}
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;
}
這里建議看下類圖,弄明白sSharedPrefs這個map的含義。這個方法從sSharedPrefs中根據包名獲取一個和這個包名對應的map,然后從這個map中獲取和傳入的name關聯的SharedPreferencesImpl對象,若不存在則創建這個對象。我們看下這個類。
final class SharedPreferencesImpl implements SharedPreferences
------------------------------成員變量-----------------------------------
private final File mFile; //保存數據的文件
private final File mBackupFile;
private final int mMode;
private Map<String, Object> mMap; //保存和該name關聯的鍵值對
------------------------------構造方法--------------------------------------
SharedPreferencesImpl(File file, int mode) {
mFile = file;
mBackupFile = makeBackupFile(file);
mMode = mode;
mLoaded = false;
mMap = null;
startLoadFromDisk(); //從文件獲取map數據
}
private void startLoadFromDisk() {
synchronized (this) {
mLoaded = false;
}
new Thread("SharedPreferencesImpl-load") {
public void run() {
synchronized (SharedPreferencesImpl.this) {
loadFromDiskLocked();//子線程中加載文件中的數據到成員變量map中
}
}
}.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); //解析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; //賦值給成員變量
mStatTimestamp = stat.st_mtime;
mStatSize = stat.st_size;
} else {
mMap = new HashMap<String, Object>();
}
notifyAll();
}
創建SharedPreferencesImpl對象的同時,會從對應的xml文件中解析數據,保存到成員變量mMap中。
到這里,我就就創建好了SharedPreferences,所以我們調用getSharedPreferences后返回的SharedPreferences就是SharedPreferencesImpl對象。
讀寫數據
首先我們要獲取一個Editor對象
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();
}
這個Editor的實現是EditorImpl,我們看下這個類:
public final class EditorImpl implements Editor
-----------------------------成員變量-------------------------------
private final Map<String, Object> mModified = Maps.newHashMap();
----------------------------核心方法---------------------------
public Editor putBoolean(String key, boolean value)
等
比如要寫入一個boolean值我們調用Editor的如下方法:
public Editor putBoolean(String key, boolean value) {
synchronized (this) {
mModified.put(key, value);
return this;
}
}
很簡單,將本次增加的鍵值對保存到mModified中,暫時緩存在內存中。
同步數據到文件
想要把數據同步到文件要調用commit()方法:
public boolean commit() {
MemoryCommitResult mcr = commitToMemory(); //mModified和mMap中的數據一并保存到MemoryCommitResult對象中
SharedPreferencesImpl.this.enqueueDiskWrite( //寫入到文件
mcr, null);
try {
mcr.writtenToDiskLatch.await();
} catch (InterruptedException e) {
return false;
}
notifyListeners(mcr);
return mcr.writeToDiskResult;
}
private void notifyListeners(final MemoryCommitResult mcr) {
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);
}
});
}
}
}
這里注意commitToMemory方法,該方法將本次修改的數據mModified和以前的數據mMap一并保存到MemoryCommitResult對象中,然后調用enqueueDiskWrite方法將內存中的數據寫入到文件。
看下commitToMemory方法:
private MemoryCommitResult commitToMemory() {
MemoryCommitResult mcr = new MemoryCommitResult(); //新建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; //將mMap保存到mcr的mapToWriteToDisk這個map中
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); //將本次修改增加的數據也加入到mMap中
}
mcr.changesMade = true;
if (hasListeners) {
mcr.keysModified.add(k);
}
}
mModified.clear();
}
}
return mcr;
}
接著看下enqueueDiskWrite是如何將數據寫入文件的:
private void enqueueDiskWrite(final MemoryCommitResult mcr,
final Runnable postWriteRunnable) {
final Runnable writeToDiskRunnable = new Runnable() {
public void run() {
synchronized (mWritingToDiskLock) {
writeToFile(mcr); //將mcr寫到文件,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(); //commit走這里,在當前線程執行
return;
}
}
QueuedWork.singleThreadExecutor().execute(writeToDiskRunnable);
}
commit方法會直接調用 writeToDiskRunnable.run(),也就是說在當前線程進行寫文件操作,我們看下writeToFile方法:
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); //使用XmlUtils.writeMapXml方法將內存中的鍵值對寫入文件
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);
}
這里主要關注兩步,首先獲取文件流,然后使用XmlUtils.writeMapXml將map寫入文件。到這里,內存中的數據就寫入到了文件。
總結
SharedPreference保存數據的形式是xml文件,并且創建時不同的name對應不同的xml文件。只有執行commit()操作才會將數據同步到文件,并且commit是同步的,會阻塞當前線程。想異步寫入可以考慮apply方法。
如果覺得寫得還不錯可以關注我哦,后面會將更多筆記的內容整理成博客。支持原創,轉載請注明出處。
來自:http://www.jianshu.com/p/1be4eb02f6a8