1.簡介
寫這篇博客目的在于鞏固自己對SharedPreferences的理解。SharePreferences是Android系統(tǒng)提供的輕量級數(shù)據(jù)存儲方案,主要基于鍵值對方式保存數(shù)據(jù)湾趾,真實(shí)的數(shù)據(jù)是保存在/data/data/packageName/shared_pref/目錄下面的麦轰。可以保存多種數(shù)據(jù)到該文件中,以下是一個簡單的Sharepreference文件藏斩。
<?xml version='1.0' encoding='utf-8' standalone='yes' ?>
<map>
<boolean name="btest" value="true" />
<string name="stest">string</string>
<int name="itest" value="999" />
<long name="ltest" value="1516358782" />
<int name="itest_1" value="2" />
</map>
從文件中可以看出就是采用簡單xml方式進(jìn)行保存的。
1.1使用實(shí)例
SharedPreferences preferences = context.getSharedPreferences("share", Context.MODE_PRIVATE);
SharedPreferences.Editor editor = preferences.edit();
editor.putBoolean("btest", true);
editor.putString("stest", "string test");
//editor.apply();//異步保存
editor.commit();//同步保存
1.2基本結(jié)構(gòu)
這里借用Gityuan博客中的類繼承圖
在Sharepreference中却盘,Sharepreference和Editor只是兩個接口狰域,在這兩個接口中定義了一個普通的鍵值對存儲的數(shù)據(jù)一些常用的操作媳拴。然后具體你想把這鍵值對存哪,你可以自己定義相應(yīng)的文件或數(shù)據(jù)庫兆览,甚至你可以寫個保存到網(wǎng)絡(luò)中去屈溉。在Android系統(tǒng)中給出的是采用xml方式存在xml的文件中,具體實(shí)現(xiàn)類是SharepreferenceImpl和SharepreferenceImpl.EditorImpl抬探。同時在ContextImpl中有Sharepreference的對應(yīng)內(nèi)存中的數(shù)據(jù)子巾。
2.Sharepreference源碼分析
2.1獲取Sharepreference
Activity.java
public SharedPreferences getPreferences(int mode) {
return getSharedPreferences(getLocalClassName(), mode);
}
@Override
public SharedPreferences getSharedPreferences(String name, int mode) {
return mBase.getSharedPreferences(name, mode);
}
Context采用的是裝飾模式,其中正在干活的是ContextImpl小压,mBase即為ContextImpl线梗,具體代碼如下:
ContextImpl.java
//ContextImpl類中的靜態(tài)Map聲明,全局的一個sSharedPrefs
private static ArrayMap<String, ArrayMap<String, SharedPreferencesImpl>> sSharedPrefs;
@Override
public SharedPreferences getSharedPreferences(String name, int mode) {
SharedPreferencesImpl sp;
synchronized (ContextImpl.class) {
if (sSharedPrefs == null) { //靜態(tài)變量怠益,全局唯一
sSharedPrefs = new ArrayMap<String, ArrayMap<String, SharedPreferencesImpl>>();
}
final String packageName = getPackageName();//通過包名找到對應(yīng)的prefs集合
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);//這里獲取sp
if (sp == null) {//如果為空仪搔,則構(gòu)建一個sp,并將它放入packagePrefs里面
File prefsFile = getSharedPrefsFile(name);//正在獲取文件的地方
sp = new SharedPreferencesImpl(prefsFile, mode);
packagePrefs.put(name, sp);
return sp;
}
}
//下面是為了跨進(jìn)程使用Sharepreference的蜻牢,跨進(jìn)程使用也就是重新裝載一次sharepreference
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;
}
正在保存的文件獲取是getSharedPrefsFile(name)僻造,代碼如下:
@Override
public File getSharedPrefsFile(String name) { //文件以.xml結(jié)尾
return makeFilename(getPreferencesDir(), name + ".xml");
}
private File makeFilename(File base, String name) {
if (name.indexOf(File.separatorChar) < 0) { //name中不能存在文件路徑分隔符
return new File(base, name);
}
throw new IllegalArgumentException(
"File " + name + " contains a path separator");
}
private File getPreferencesDir() {//sharepreference文件的目錄/data/data/{包名}/shared_prefs
synchronized (mSync) {
if (mPreferencesDir == null) {
mPreferencesDir = new File(getDataDirFile(), "shared_prefs");
}
return mPreferencesDir;
}
}
在ContextImpl中存在一個靜態(tài)的sSharedPrefs,通過它來獲取對應(yīng)應(yīng)用的prefs孩饼,在通過prefs找到對應(yīng)名稱的Sharepreference的引用。在系統(tǒng)中共用一個sSharedPrefs竹挡,每個應(yīng)該在獲取sp的時候都會將創(chuàng)建后sp加入到sSharedPrefs中以便后續(xù)進(jìn)行訪問镀娶。
2.2 SharepreferenceImpl
從上面我們可以看到我們要獲取的是Sharepreference,但是返回的是SharepreferenceImpl揪罕,這就赤裸裸的告訴我們SharepreferenceImpl是Sharepreference接口的實(shí)現(xiàn)類梯码,具體代碼如下:
final class SharedPreferencesImpl implements SharedPreferences {
private static final String TAG = "SharedPreferencesImpl";
private static final boolean DEBUG = false;
// Lock ordering rules:
// - acquire SharedPreferencesImpl.this before EditorImpl.this
// - acquire mWritingToDiskLock before EditorImpl.this
private final File mFile;
private final File mBackupFile;
private final int mMode;
private Map<String, Object> mMap; // guarded by 'this'
private int mDiskWritesInFlight = 0; // guarded by 'this'
private boolean mLoaded = false; // guarded by 'this'
private long mStatTimestamp; // guarded by 'this'
private long mStatSize; // guarded by 'this'
private final Object mWritingToDiskLock = new Object();
private static final Object mContent = new Object();
private final WeakHashMap<OnSharedPreferenceChangeListener, Object> mListeners =
new WeakHashMap<OnSharedPreferenceChangeListener, Object>();
SharedPreferencesImpl(File file, int mode) {
mFile = file;
mBackupFile = makeBackupFile(file); //創(chuàng)建臨時備份文件,這樣寫入失敗的時候就用這個備份的還原
mMode = mode;
mLoaded = false;
mMap = null;
startLoadFromDisk();//異步加載文件內(nèi)容到內(nèi)存
}
private void startLoadFromDisk() {
synchronized (this) {
mLoaded = false;
}
new Thread("SharedPreferencesImpl-load") {
public void run() {
//由于是多線程加載的時候注意同步處理
synchronized (SharedPreferencesImpl.this) {
loadFromDiskLocked();
}
}
}.start();
}
...
private static File makeBackupFile(File prefsFile) {
return new File(prefsFile.getPath() + ".bak");
}
...
}
在獲取sp的時候好啰,如果通過sSharedPrefs獲取為空就會先創(chuàng)建一個sp轩娶,在new SharepreferenceImpl的時候,在構(gòu)造函數(shù)中最后就會異步加載文件到內(nèi)存框往,異步開啟一個線程后就調(diào)用loadFromDiskLocked()函數(shù)進(jìn)行加載:
SharepreferenceImpl.java
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);//利用XmlUtils進(jìn)行解析
} 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();//沒加載完前鳄抒,所有操作(get等)都會等待加載完成,加載完成后通知其他操作可以進(jìn)行操作了椰弊。
}
一旦加載完成后许溅,就會notifyAll(),我們先看下get的操作
public Map<String, ?> getAll() {
synchronized (this) {
awaitLoadedLocked();
//noinspection unchecked
return new HashMap<String, Object>(mMap);
}
}
@Nullable
public String getString(String key, @Nullable String defValue) {
synchronized (this) {
awaitLoadedLocked();//沒有加載就阻塞等待
String v = (String)mMap.get(key);//加載完成了就直接去內(nèi)存中的值秉版,記住是從內(nèi)存中取贤重。不會再次讀取文件總內(nèi)容。
return v != null ? v : defValue;
}
}
...
private void awaitLoadedLocked() {//這里判斷是否已經(jīng)加載文件到內(nèi)存了清焕,沒有加載就會阻塞等待
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) {
}
}
}
在get數(shù)據(jù)時并蝗,首先判斷文件是否加載到內(nèi)存祭犯,然后就直接讀取內(nèi)存中的值,這里可以看出一旦裝載了滚停,那么讀取的速度就很快沃粗。
2.3 EditorImpl
上面SharepreferenceImpl是實(shí)現(xiàn)了get操作,真正的寫入是Editor接口來完成的铐刘,而EditorImpl是具體的實(shí)現(xiàn)類陪每。其代碼如下:
public final class EditorImpl implements Editor {
private final Map<String, Object> mModified = Maps.newHashMap();
private boolean mClear = false;
//從這里可以看出每次存的時候都是先存入內(nèi)存中的mModified變量中
public Editor putString(String key, @Nullable String value) {
synchronized (this) {
mModified.put(key, value);
return this;
}
}
public Editor putStringSet(String key, @Nullable Set<String> values) {
synchronized (this) {
mModified.put(key,
(values == null) ? null : new HashSet<String>(values));
return this;
}
}
public Editor putInt(String key, int value) {
synchronized (this) {
mModified.put(key, value);
return this;
}
}
...
public Editor remove(String key) {
synchronized (this) {
mModified.put(key, this);
return this;
}
}
public Editor clear() {
synchronized (this) {
mClear = true;
return this;
}
}
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);
}
}
首先查看下存入的代碼:
//從這里可以看出每次存的時候都是先存入內(nèi)存中的mModified變量中
public Editor putString(String key, @Nullable String value) {
synchronized (this) {
mModified.put(key, value);
return this;
}
}
存入的時候首先獲取同步鎖,然后將存入的數(shù)據(jù)放入EditorImpl中的一個mModified變量中镰吵,也就是存入的時候并沒有放入Sharepreference中檩禾,只有在使用了apply或者commit后才真正存入。
下面來看看commit操作:
public boolean commit() {
MemoryCommitResult mcr = commitToMemory();//步驟1
SharedPreferencesImpl.this.enqueueDiskWrite(
mcr, null /* sync write on this thread okay */);//步驟2
try {
mcr.writtenToDiskLatch.await();//等待寫入完成
} catch (InterruptedException e) {
return false;
}
notifyListeners(mcr);//步驟3
return mcr.writeToDiskResult;步驟4
}
步驟1:
// 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.
//刪除一些需要刪除的數(shù)據(jù)
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;
}
}
//將變化的數(shù)據(jù)放入SharepreferenceImpl的mMap中
mMap.put(k, v);
}
mcr.changesMade = true;
if (hasListeners) {
mcr.keysModified.add(k);
}
}
//變化的數(shù)據(jù)都加入了mMap后就可以清除mModified內(nèi)容了疤祭。
mModified.clear();
}
}
//返回封裝mMap的MemoryCommitResult數(shù)據(jù)
return mcr;
}
步驟2:
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);//如果postWriteRunnable為null就是同步
// Typical #commit() path with fewer allocations, doing a write on
// the current thread.
if (isFromSyncCommit) {//同步就直接運(yùn)行寫入數(shù)據(jù)writeToDiskRunnable
boolean wasEmpty = false;
synchronized (SharedPreferencesImpl.this) {
wasEmpty = mDiskWritesInFlight == 1;
}
if (wasEmpty) {
writeToDiskRunnable.run();
return;
}
}
QueuedWork.singleThreadExecutor().execute(writeToDiskRunnable);
}
// 寫入數(shù)據(jù)
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);
}
步驟3通知寫入數(shù)據(jù)發(fā)生變化
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);
}
});
}
}
步驟4返回寫入的結(jié)果盼产。
2.3.2 Editor.apply()
代碼如下:
public void apply() {
//寫數(shù)據(jù)到內(nèi)存,返回數(shù)據(jù)結(jié)構(gòu)
final MemoryCommitResult mcr = commitToMemory();
final Runnable awaitCommit = new Runnable() {
public void run() {
try {
//等待寫文件結(jié)束
mcr.writtenToDiskLatch.await();
} catch (InterruptedException ignored) {
}
}
};
QueuedWork.add(awaitCommit);
//一個收尾的Runnable
Runnable postWriteRunnable = new Runnable() {
public void run() {
awaitCommit.run();
QueuedWork.remove(awaitCommit);
}
};
//這里postWriteRunnable不為null勺馆,所以會在一個新的線程池調(diào)運(yùn)postWriteRunnable的run方法
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);
}
apply會將寫入放入到一個線程池中操作戏售,這不會阻塞調(diào)用的線程。其他的都和commit類似草穆。
QueuedWork.java
public class QueuedWork {
private static final ConcurrentLinkedQueue<Runnable> sPendingWorkFinishers =
new ConcurrentLinkedQueue<Runnable>();
public static void add(Runnable finisher) {
sPendingWorkFinishers.add(finisher);
}
public static void remove(Runnable finisher) {
sPendingWorkFinishers.remove(finisher);
}
public static void waitToFinish() {
Runnable toFinish;
while ((toFinish = sPendingWorkFinishers.poll()) != null) {
toFinish.run();
}
}
public static boolean hasPendingWork() {
return !sPendingWorkFinishers.isEmpty();
}
}
總結(jié)
apply 與commit的對比
apply沒有返回值, commit有返回值能知道修改是否提交成功
apply是將修改提交到內(nèi)存灌灾,再異步提交到磁盤文件; commit是同步的提交到磁盤文件;
多并發(fā)的提交commit時,需等待正在處理的commit數(shù)據(jù)更新到磁盤文件后才會繼續(xù)往下執(zhí)行悲柱,從而降低效率; 而apply只是原子更新到內(nèi)存锋喜,后調(diào)用apply函數(shù)會直接覆蓋前面內(nèi)存數(shù)據(jù),從一定程度上提高很多效率豌鸡。
獲取SP與Editor:
getSharedPreferences()是從ContextImpl.sSharedPrefsCache唯一的SPI對象;
edit()每次都是創(chuàng)建新的EditorImpl對象.
優(yōu)化建議:
強(qiáng)烈建議不要在sp里面存儲特別大的key/value, 有助于減少卡頓/anr
請不要高頻地使用apply, 盡可能地批量提交;commit直接在主線程操作, 更要注意了
不要使用MODE_MULTI_PROCESS;
高頻寫操作的key與高頻讀操作的key可以適當(dāng)?shù)夭鸱治募? 由于減少同步鎖競爭;
不要一上來就執(zhí)行g(shù)etSharedPreferences().edit(), 應(yīng)該分成兩大步驟來做, 中間可以執(zhí)行其他代碼.
不要連續(xù)多次edit(), 應(yīng)該獲取一次獲取edit(),然后多次執(zhí)行putxxx(), 減少內(nèi)存波動; 經(jīng)澈侔悖看到大家喜歡封裝方法, 結(jié)果就導(dǎo)致這種情況的出現(xiàn).
每次commit時會把全部的數(shù)據(jù)更新的文件, 所以整個文件是不應(yīng)該過大的, 影響整體性能;