打开
一般我们使用 SharedPreferences 都是直接或者间接调用 ContextImpl
类的getSharedPreferences
方法,我们看一下这个方法的代码
public SharedPreferences getSharedPreferences(String name, int mode) {
SharedPreferencesImpl sp;
synchronized (ContextImpl.class) {
if (sSharedPrefs == null) {
sSharedPrefs = new ArrayMap>();
}
final String packageName = getPackageName();
ArrayMap packagePrefs = sSharedPrefs.get(packageName);
if (packagePrefs == null) {
packagePrefs = new ArrayMap();
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;
}
从源码中可以看到,首先设置了一些Map用来缓存数据,其次根据名称获取本地的文件,最后创建 SharedPreferencesImpl
类, SharedPreferencesImpl
类是 SharedPreferences
接口的具体实现。在 SharedPreferencesImpl
类的构造方法中通过线程将文件读取到内存中,具体代码如下:
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();
}
notifyAll();
}
首先 loadFromDiskLocked()
方法是在新创建的线程中执行所以不用担心阻塞主线程,在方法开始的地方首先检查上次数据保存是否异常,如果有异常则恢复异常发生之前的数据。然后通过 XmlUtils.readMapXml()
方法将文件中的数据读取到一个 HashMap 中,这里也可以看出数据在文件中是以xml格式存储的
读取
读取数据比较简单通过 getBoolean()
可以简单看出数据读取的流程
public boolean getBoolean(String key, boolean defValue) {
synchronized (this) {
awaitLoadedLocked();
Boolean v = (Boolean)mMap.get(key);
return v != null ? v : defValue;
}
}
其中 awaitLoadedLocked()
等待数据从文件中读取完毕,然后将数据从Map中取出。
写入
让我们来看一下写入的一般用法
SharedPreferences sp = getSharedPreferences(name, mode);
Editor editor = sp.edit();
editor.putBoolean(key, true);
editor.commit(); //editor.apply();
我们逐行来分析写入的过程
第一行 getSharedPreferences()
在上面已经分析过,这里不再赘述
第二行通过 sp.edit()
获取到一个 Editor,这里看一下具体实现
public Editor edit() {
synchronized (this) {
awaitLoadedLocked();
}
return new EditorImpl();
}
这里首先等待数据读取完毕,然后创建一个 EditorImpl 对象,其中EditorImpl是Editor的具体实现
第三行代码通过 putBoolean()
方法将数据存储到内部的一个Map中,其中比较有意思的是 remove(key)
和 clear()
两个方法
public Editor remove(String key) {
synchronized (this) {
mModified.put(key, this);
return this;
}
}
public Editor clear() {
synchronized (this) {
mClear = true;
return this;
}
}
在 clear
方法中设置了一个清除的标记位,而在 remove
方法中就很有意思了,将Editor自身存储到了Map中,那么在数据写入到文件中的时候到底是如何处理的呢,我们接着看最后写入磁盘的过程
写入的方法有两种, commit 和 apply 两种,两种实现有一些区别(废话),先来看 commit 的实现
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()
方法中做了三件事情,将数据从 Editor 中拷贝到 SharedPreferences 中(可以称之为提交到内存中),将数据写入到文件中,通知监听器
首先看一下提交到内存的过程
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(mMap);
}
mcr.mapToWriteToDisk = mMap;
mDiskWritesInFlight++;
boolean hasListeners = mListeners.size() > 0;
if (hasListeners) {
mcr.keysModified = new ArrayList();
mcr.listeners =
new HashSet(mListeners.keySet());
}
synchronized (this) {
if (mClear) {
if (!mMap.isEmpty()) {
mcr.changesMade = true;
mMap.clear();
}
mClear = false;
}
for (Map.Entry 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;
}
首先检查是否有数据正在写入到磁盘中,如果有,需要做一次深拷贝。接着检查 mClear 标志,这个标志是在调用 editor.clear()
的时候设置的,如果设置了就会将原来存储在Map中的数据全部删除。紧接着通过一个for循环,遍历Editor中Map的数据。首先检查value是否是Editor本身(在调用 editor.remove()
的时候设置)或者为 null ,如果是,删除SharedPreferences中Map对应的数据。否则就会将数据添加到Map中。遍历完成后将原有Editor中的Map数据清空,至此完成了内存数据的拷贝
下面看一下写入到文件的过程
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);
}
首先创建一个 writeToDiskRunnable ,将具体的写入逻辑封装起来。然后判断是否调用的 commit()
方法,如果是,并且当前只有一个写入请求的话,就在当前线程中执行写入操作,否则,将写入操作添加到线程池中执行
下面分析写入操作的过程
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);
}
首先判断本次提交是否有数据更改,如果没有,则不需要写入任何内容,否则将保存着旧数据的文件备份起来。然后通过 XmlUtils.writeMapXml()
方法将数据写入到文件中,并设置相应的访问权限。如果写入成功,将备份文件删除,至此一次 commit()
数据写入操作结束