一、概述
剛開始學習Loader
的時候,只是使用CursorLoader
把它當作載入封裝在ContentProvider
中的資料的一種方式,但是如果我們學會了如何取定義自己的Loader
,那麼將不僅僅侷限於讀取ContentProvider
的資料,在谷歌的藍圖框架中,就有一個分支是介紹如何使用Loader
來實現資料的非同步讀取:
https://github.com/googlesamples/android-architecture/tree/todo-mvp-loaders/
我們現在來學習一下Loader
的實現原理,這將幫助我們知道如何自定義自己的Loader
來進行非同步資料的載入。
二、Activity
和LoaderManager
的橋樑 - FragmentHostCallback
如果我們把Loader
比喻為非同步任務的執行者,那麼LoaderManager
就是這些執行者的管理者,而LoaderManager
對於Loader
的管理又會依賴於Activity/Fragment
的生命週期。
在整個系統當中,LoaderManager
和Activity/Fragment
之間的關係是通過FragmentHostCallback
這個中介者維繫的,當Activity
或者Fragment
的關鍵生命週期被回撥時,會呼叫FragmentHostCallback
的對應方法,它再通過內部持有的LoaderManager
例項來控制每個LoaderManager
內的Loader
。
在FragmentHostCallback
當中,和Loader
有關的成員變數包括:
/** The loader managers for individual fragments [i.e. Fragment#getLoaderManager()] */
private ArrayMap<String, LoaderManager> mAllLoaderManagers;
/** Whether or not fragment loaders should retain their state */
private boolean mRetainLoaders;
/** The loader manger for the fragment host [i.e. Activity#getLoaderManager()] */
private LoaderManagerImpl mLoaderManager;
private boolean mCheckedForLoaderManager;
/** Whether or not the fragment host loader manager was started */
private boolean mLoadersStarted;
複製程式碼
mAllLoaderManagers
:和Fragment
關聯的LoaderManager
,每個Fragment
對應一個LoaderManager
。mRetainLoaders
:**Fragment
的Loader
**是否要保持它們的狀態。mLoaderManager
:和Fragment
宿主關聯的LoaderManager
。mCheckedForLoaderManager
:當Fragment
的宿主的LoaderManager
被建立以後,該標誌位變為true
。mLoadersStarted
:**Fragment
的宿主的Loader
**是否已經啟動。
FragmentHostCallback
的doXXX
和Activity
的物件關係
下面是整理的表格:
restoreLoaderNonConfig
<-onCreate
reportLoaderStart
<-performStart
doLoaderStart
<-onStart/retainNonConfigurationInstances
doLoaderStop(true/false)
<-performStop/retainNonConfigurationInstances
retainLoaderNonConfig
<-retainNonConfigurationInstances
doLoaderDestroy
<-performDestroy
doLoaderRetain
<-null
其中有個函式比較陌生,retainNonConfigurationInstances
,我們看一下它的含義:
NonConfigurationInstances retainNonConfigurationInstances() {
Object activity = onRetainNonConfigurationInstance();
HashMap<String, Object> children = onRetainNonConfigurationChildInstances();
FragmentManagerNonConfig fragments = mFragments.retainNestedNonConfig();
//由於要求儲存loader的狀態,所以我們需要標誌loader,為此,我們需要在將它交給下個Activity之前重啟一下loader
mFragments.doLoaderStart();
mFragments.doLoaderStop(true);
ArrayMap<String, LoaderManager> loaders = mFragments.retainLoaderNonConfig();
if (activity == null && children == null && fragments == null && loaders == null
&& mVoiceInteractor == null) {
return null;
}
NonConfigurationInstances nci = new NonConfigurationInstances();
nci.activity = activity;
nci.children = children;
nci.fragments = fragments;
nci.loaders = loaders;
if (mVoiceInteractor != null) {
mVoiceInteractor.retainInstance();
nci.voiceInteractor = mVoiceInteractor;
}
return nci;
}
複製程式碼
我們看到,它儲存了大量的資訊,最後返回一個NonConfigurationInstances
,因此我們猜測它和onSaveInstance
的作用是類似的,在attach
方法中,傳入了lastNonConfigurationInstances
,之後我們就可以通過getLastNonConfigurationInstance
來得到它,但是需要注意,這個變數在performResume
之後就會清空。
通過ActivityThread
的原始碼,我們可以看到,這個方法是在onStop
到onDestory
之間呼叫的。
//呼叫onStop()
r.activity.performStop(r.mPreserveWindow);
//呼叫retainNonConfigurationInstances
r.lastNonConfigurationInstances = r.activity.retainNonConfigurationInstances();
//呼叫onDestroy().
mInstrumentation.callActivityOnDestroy(r.activity);
複製程式碼
總結下來,就是一下幾點:
- 在
onStart
時啟動Loader
- 在
onStop
時停止Loader
- 在
onDestory
時銷燬Loader
- 在配置發生變化時儲存
Loader
三、LoaderManager/LoaderManagerImpl
的含義
通過上面,我們就可以瞭解系統是怎麼根據Activity/Fragment
的生命週期來自動管理Loader
的了,現在,我們來看一下LoaderManagerImpl
的具體實現,這兩個類的關係是:
LoaderManager
:這是一個抽象類,它內部定義了LoaderCallbacks
介面,在loader
的狀態發生改變時會通過這個回撥通知使用者,此外,它還定義了三個關鍵的抽象方法,呼叫者只需要使用這三個方法就能完成資料的非同步載入。LoaderManagerImpl
:繼承於LoaderManager
,真正地實現了Loader
的管理。
四、LoaderManager
的介面定義
public abstract class LoaderManager {
/**
* Callback interface for a client to interact with the manager.
*/
public interface LoaderCallbacks<D> {
/**
* Instantiate and return a new Loader for the given ID.
*
* @param id The ID whose loader is to be created.
* @param args Any arguments supplied by the caller.
* @return Return a new Loader instance that is ready to start loading.
*/
public Loader<D> onCreateLoader(int id, Bundle args);
/**
* Called when a previously created loader has finished its load. Note
* that normally an application is <em>not</em> allowed to commit fragment
* transactions while in this call, since it can happen after an
* activity's state is saved. See {@link FragmentManager#beginTransaction()
* FragmentManager.openTransaction()} for further discussion on this.
*
* <p>This function is guaranteed to be called prior to the release of
* the last data that was supplied for this Loader. At this point
* you should remove all use of the old data (since it will be released
* soon), but should not do your own release of the data since its Loader
* owns it and will take care of that. The Loader will take care of
* management of its data so you don't have to. In particular:
*
* <ul>
* <li> <p>The Loader will monitor for changes to the data, and report
* them to you through new calls here. You should not monitor the
* data yourself. For example, if the data is a {@link android.database.Cursor}
* and you place it in a {@link android.widget.CursorAdapter}, use
* the {@link android.widget.CursorAdapter#CursorAdapter(android.content.Context,
* android.database.Cursor, int)} constructor <em>without</em> passing
* in either {@link android.widget.CursorAdapter#FLAG_AUTO_REQUERY}
* or {@link android.widget.CursorAdapter#FLAG_REGISTER_CONTENT_OBSERVER}
* (that is, use 0 for the flags argument). This prevents the CursorAdapter
* from doing its own observing of the Cursor, which is not needed since
* when a change happens you will get a new Cursor throw another call
* here.
* <li> The Loader will release the data once it knows the application
* is no longer using it. For example, if the data is
* a {@link android.database.Cursor} from a {@link android.content.CursorLoader},
* you should not call close() on it yourself. If the Cursor is being placed in a
* {@link android.widget.CursorAdapter}, you should use the
* {@link android.widget.CursorAdapter#swapCursor(android.database.Cursor)}
* method so that the old Cursor is not closed.
* </ul>
*
* @param loader The Loader that has finished.
* @param data The data generated by the Loader.
*/
public void onLoadFinished(Loader<D> loader, D data);
/**
* Called when a previously created loader is being reset, and thus
* making its data unavailable. The application should at this point
* remove any references it has to the Loader's data.
*
* @param loader The Loader that is being reset.
*/
public void onLoaderReset(Loader<D> loader);
}
/**
* Ensures a loader is initialized and active. If the loader doesn't
* already exist, one is created and (if the activity/fragment is currently
* started) starts the loader. Otherwise the last created
* loader is re-used.
*
* <p>In either case, the given callback is associated with the loader, and
* will be called as the loader state changes. If at the point of call
* the caller is in its started state, and the requested loader
* already exists and has generated its data, then
* callback {@link LoaderCallbacks#onLoadFinished} will
* be called immediately (inside of this function), so you must be prepared
* for this to happen.
*
* @param id A unique identifier for this loader. Can be whatever you want.
* Identifiers are scoped to a particular LoaderManager instance.
* @param args Optional arguments to supply to the loader at construction.
* If a loader already exists (a new one does not need to be created), this
* parameter will be ignored and the last arguments continue to be used.
* @param callback Interface the LoaderManager will call to report about
* changes in the state of the loader. Required.
*/
public abstract <D> Loader<D> initLoader(int id, Bundle args,
LoaderManager.LoaderCallbacks<D> callback);
/**
* Starts a new or restarts an existing {@link android.content.Loader} in
* this manager, registers the callbacks to it,
* and (if the activity/fragment is currently started) starts loading it.
* If a loader with the same id has previously been
* started it will automatically be destroyed when the new loader completes
* its work. The callback will be delivered before the old loader
* is destroyed.
*
* @param id A unique identifier for this loader. Can be whatever you want.
* Identifiers are scoped to a particular LoaderManager instance.
* @param args Optional arguments to supply to the loader at construction.
* @param callback Interface the LoaderManager will call to report about
* changes in the state of the loader. Required.
*/
public abstract <D> Loader<D> restartLoader(int id, Bundle args,
LoaderManager.LoaderCallbacks<D> callback);
/**
* Stops and removes the loader with the given ID. If this loader
* had previously reported data to the client through
* {@link LoaderCallbacks#onLoadFinished(Loader, Object)}, a call
* will be made to {@link LoaderCallbacks#onLoaderReset(Loader)}.
*/
public abstract void destroyLoader(int id);
/**
* Return the Loader with the given id or null if no matching Loader
* is found.
*/
public abstract <D> Loader<D> getLoader(int id);
/**
* Returns true if any loaders managed are currently running and have not
* returned data to the application yet.
*/
public boolean hasRunningLoaders() { return false; }
}
複製程式碼
這一部分,我們先根據原始碼的註釋對這些方法有一個大概的瞭解:
-
public Loader<D> onCreateLoader(int id, Bundle args)
-
當
LoaderManager
需要建立一個Loader
時,回撥該函式來要求使用者提供一個Loader
,而id
為這個Loader
的唯一標識。 -
public void onLoadFinished(Loader<D> loader, D data)
-
當之前建立的
Loader
完成了任務之後回撥,data
就是得到的資料。 -
回撥時,可能
Activity
已經呼叫了onSaveInstanceState
,因此不建議在其中提交Fragment
事務。 -
這個方法會保證資料資源在被釋放之前呼叫,例如,當使用
CursorLoader
時,LoaderManager
會負責cursor
的關閉。 -
LoaderManager
會主動監聽資料的變化。 -
public void onLoaderReset(Loader<D> loader)
-
當先前建立的某個
Loader
被reset
時回撥。 -
呼叫者應當在收到該回撥以後移除與舊
Loader
有關的資料。 -
public abstract <D> Loader<D> initLoader(int id, Bundle args, LoaderManager.LoaderCallbacks<D> callback)
-
用來初始化和啟用
Loader
,args
一般用來放入查詢的條件。 -
如果
id
對應的Loader
之前不存在,那麼會建立一個新的,如果此時Activity/Fragment
已經處於started
狀態,那麼會啟動這個Loader
。 -
如果
id
對應的Loader
之前存在,那麼會複用之前的Loader
,並且忽略Bundle
引數,它僅僅是使用新的callback
。 -
如果呼叫此方法時,滿足
2
個條件:呼叫者處於started
狀態、Loader
已經存在並且產生了資料,那麼onLoadFinished
會立刻被回撥。 -
這個方法一般來說應該在元件被初始化呼叫。
-
public abstract <D> Loader<D> restartLoader(int id, Bundle args, LoaderManager.LoaderCallbacks<D> callback)
-
啟動一個新的
Loader
或者重新啟動一箇舊的Loader
,如果此時Activity/Fragment
已經處於Started
狀態,那麼會開始loading
過程。 -
如果一個相同
id
的loader
之前已經存在了,那麼當新的loader
完成工作之後,會銷燬舊的loader
,在舊的Loader
已經被destroyed
之前,會回撥對應的callback
。 -
因為
initLoader
會忽略Bundle
引數,所以當我們的查詢需要依賴於bundle
內的引數時,那麼就需要使用這個方法。 -
public abstract void destroyLoader(int id)
-
停止或者移除對應
id
的loader
。 -
如果這個
loader
之前已經回撥過了onLoadFinished
方法,那麼onLoaderReset
會被回撥,引數就是要銷燬的那個Loader
例項。 -
public abstract <D> Loader<D> getLoader(int id)
-
返回對應
id
的loader
。 -
public boolean hasRunningLoaders()
-
是否有正在執行,但是沒有返回資料的
loader
。
#五、LoaderInfo
LoaderInfo
包裝了 Loader
,其中包含了狀態變數提供給 LoaderManager
,並且在構造時候傳入了 LoaderManager.LoaderCallbacks<Object>
,這也是回撥給我們呼叫者的地方,裡面的邏輯很複雜,我們主要關注這3個方法在什麼時候被呼叫:
final class LoaderInfo implements Loader.OnLoadCompleteListener<Object>,
Loader.OnLoadCanceledListener<Object> {
final int mId; //唯一標識 Loader。
final Bundle mArgs; //查詢引數。
LoaderManager.LoaderCallbacks<Object> mCallbacks; //給呼叫者的回撥。
Loader<Object> mLoader;
boolean mHaveData;
boolean mDeliveredData;
Object mData;
@SuppressWarnings("hiding")
boolean mStarted;
@SuppressWarnings("hiding")
boolean mRetaining;
@SuppressWarnings("hiding")
boolean mRetainingStarted;
boolean mReportNextStart;
boolean mDestroyed;
boolean mListenerRegistered;
LoaderInfo mPendingLoader;
public LoaderInfo(int id, Bundle args, LoaderManager.LoaderCallbacks<Object> callbacks) {
mId = id;
mArgs = args;
mCallbacks = callbacks;
}
void start() {
if (mRetaining && mRetainingStarted) {
//Activity中正在恢復狀態,所以我們什麼也不做。
mStarted = true;
return;
}
if (mStarted) {
//已經開始了,那麼返回。
return;
}
mStarted = true;
//如果Loader沒有建立,那麼建立讓使用者去建立它。
if (mLoader == null && mCallbacks != null) {
mLoader = mCallbacks.onCreateLoader(mId, mArgs); //onCreateLoader()
}
if (mLoader != null) {
if (mLoader.getClass().isMemberClass()
&& !Modifier.isStatic(mLoader.getClass().getModifiers())) {
throw new IllegalArgumentException(
"Object returned from onCreateLoader must not be a non-static inner member class: "
+ mLoader);
}
//註冊監聽,onLoadCanceled和OnLoadCanceledListener,因為LoaderInfo實現了這兩個介面,因此把它自己傳進去。
if (!mListenerRegistered) {
mLoader.registerListener(mId, this);
mLoader.registerOnLoadCanceledListener(this);
mListenerRegistered = true;
}
//Loader開始工作。
mLoader.startLoading();
}
}
//恢復之前的狀態。
void retain() {
if (DEBUG) Log.v(TAG, " Retaining: " + this);
mRetaining = true; //正在恢復
mRetainingStarted = mStarted; //恢復時的狀態
mStarted = false;
mCallbacks = null;
}
//狀態恢復完之後呼叫。
void finishRetain() {
if (mRetaining) {
if (DEBUG) Log.v(TAG, " Finished Retaining: " + this);
mRetaining = false;
if (mStarted != mRetainingStarted) {
if (!mStarted) {
//如果在恢復完後發現,它已經不處於Started狀態,那麼停止。
stop();
}
}
}
if (mStarted && mHaveData && !mReportNextStart) {
// This loader has retained its data, either completely across
// a configuration change or just whatever the last data set
// was after being restarted from a stop, and now at the point of
// finishing the retain we find we remain started, have
// our data, and the owner has a new callback... so
// let's deliver the data now.
callOnLoadFinished(mLoader, mData);
}
}
void reportStart() {
if (mStarted) {
if (mReportNextStart) {
mReportNextStart = false;
if (mHaveData) {
callOnLoadFinished(mLoader, mData);
}
}
}
}
void stop() {
if (DEBUG) Log.v(TAG, " Stopping: " + this);
mStarted = false;
if (!mRetaining) {
if (mLoader != null && mListenerRegistered) {
// Let the loader know we're done with it
mListenerRegistered = false;
mLoader.unregisterListener(this);
mLoader.unregisterOnLoadCanceledListener(this);
mLoader.stopLoading();
}
}
}
void cancel() {
if (DEBUG) Log.v(TAG, " Canceling: " + this);
if (mStarted && mLoader != null && mListenerRegistered) {
if (!mLoader.cancelLoad()) {
onLoadCanceled(mLoader);
}
}
}
void destroy() {
if (DEBUG) Log.v(TAG, " Destroying: " + this);
mDestroyed = true;
boolean needReset = mDeliveredData;
mDeliveredData = false;
if (mCallbacks != null && mLoader != null && mHaveData && needReset) {
if (DEBUG) Log.v(TAG, " Reseting: " + this);
String lastBecause = null;
if (mHost != null) {
lastBecause = mHost.mFragmentManager.mNoTransactionsBecause;
mHost.mFragmentManager.mNoTransactionsBecause = "onLoaderReset";
}
try {
mCallbacks.onLoaderReset(mLoader);
} finally {
if (mHost != null) {
mHost.mFragmentManager.mNoTransactionsBecause = lastBecause;
}
}
}
mCallbacks = null;
mData = null;
mHaveData = false;
if (mLoader != null) {
if (mListenerRegistered) {
mListenerRegistered = false;
mLoader.unregisterListener(this);
mLoader.unregisterOnLoadCanceledListener(this);
}
mLoader.reset();
}
if (mPendingLoader != null) {
mPendingLoader.destroy();
}
}
@Override
public void onLoadCanceled(Loader<Object> loader) {
if (DEBUG) Log.v(TAG, "onLoadCanceled: " + this);
if (mDestroyed) {
if (DEBUG) Log.v(TAG, " Ignoring load canceled -- destroyed");
return;
}
if (mLoaders.get(mId) != this) {
// This cancellation message is not coming from the current active loader.
// We don't care about it.
if (DEBUG) Log.v(TAG, " Ignoring load canceled -- not active");
return;
}
LoaderInfo pending = mPendingLoader;
if (pending != null) {
// There is a new request pending and we were just
// waiting for the old one to cancel or complete before starting
// it. So now it is time, switch over to the new loader.
if (DEBUG) Log.v(TAG, " Switching to pending loader: " + pending);
mPendingLoader = null;
mLoaders.put(mId, null);
destroy();
installLoader(pending);
}
}
@Override
public void onLoadComplete(Loader<Object> loader, Object data) {
if (DEBUG) Log.v(TAG, "onLoadComplete: " + this);
if (mDestroyed) {
if (DEBUG) Log.v(TAG, " Ignoring load complete -- destroyed");
return;
}
if (mLoaders.get(mId) != this) {
// This data is not coming from the current active loader.
// We don't care about it.
if (DEBUG) Log.v(TAG, " Ignoring load complete -- not active");
return;
}
LoaderInfo pending = mPendingLoader;
if (pending != null) {
// There is a new request pending and we were just
// waiting for the old one to complete before starting
// it. So now it is time, switch over to the new loader.
if (DEBUG) Log.v(TAG, " Switching to pending loader: " + pending);
mPendingLoader = null;
mLoaders.put(mId, null);
destroy();
installLoader(pending);
return;
}
// Notify of the new data so the app can switch out the old data before
// we try to destroy it.
if (mData != data || !mHaveData) {
mData = data;
mHaveData = true;
if (mStarted) {
callOnLoadFinished(loader, data);
}
}
//if (DEBUG) Log.v(TAG, " onLoadFinished returned: " + this);
// We have now given the application the new loader with its
// loaded data, so it should have stopped using the previous
// loader. If there is a previous loader on the inactive list,
// clean it up.
LoaderInfo info = mInactiveLoaders.get(mId);
if (info != null && info != this) {
info.mDeliveredData = false;
info.destroy();
mInactiveLoaders.remove(mId);
}
if (mHost != null && !hasRunningLoaders()) {
mHost.mFragmentManager.startPendingDeferredFragments();
}
}
void callOnLoadFinished(Loader<Object> loader, Object data) {
if (mCallbacks != null) {
String lastBecause = null;
if (mHost != null) {
lastBecause = mHost.mFragmentManager.mNoTransactionsBecause;
mHost.mFragmentManager.mNoTransactionsBecause = "onLoadFinished";
}
try {
if (DEBUG) Log.v(TAG, " onLoadFinished in " + loader + ": "
+ loader.dataToString(data));
mCallbacks.onLoadFinished(loader, data);
} finally {
if (mHost != null) {
mHost.mFragmentManager.mNoTransactionsBecause = lastBecause;
}
}
mDeliveredData = true;
}
}
}
複製程式碼
onCreateLoader
:在 start()
方法中,如果我們發現 mLoader
沒有建立,那麼通知呼叫者建立它。
onLoaderReset
:在 destroy()
方法中,也就是Loader
被銷燬時呼叫,它的呼叫需要滿足以下條件:
mHaveData == true:mHaveData
被置為true
的地方是在onLoadComplete
中判斷到有新的資料,並且之前mHaveData == false
,在onDestroy
時置為false
。mDeliveredData == true
:它在callOnLoadFinished
時被置為true
,成功地回撥了呼叫者的onLoadFinished
- 這兩個條件一結合,就可以知道這是一個已經遞交過資料的
loader
,所以在destory
的時候,就要通知呼叫者loader
被替換了。
六、LoaderManagerImpl
實現的三個關鍵方法
6.1 initLoader
的實現
public <D> Loader<D> initLoader(int id, Bundle args, LoaderManager.LoaderCallbacks<D> callback) {
//createAndInstallLoader方法正在執行,丟擲異常。
if (mCreatingLoader) {
throw new IllegalStateException("Called while creating a loader");
}
LoaderInfo info = mLoaders.get(id);
if (info == null) {
info = createAndInstallLoader(id, args, (LoaderManager.LoaderCallbacks<Object>)callback);
} else {
info.mCallbacks = (LoaderManager.LoaderCallbacks<Object>)callback;
}
//如果已經有資料,並且處於LoaderManager處於Started狀態,那麼立刻返回。
if (info.mHaveData && mStarted) {
info.callOnLoadFinished(info.mLoader, info.mData);
}
return (Loader<D>) info.mLoader;
}
private LoaderInfo createAndInstallLoader(int id, Bundle args, LoaderManager.LoaderCallbacks<Object> callback) {
try {
mCreatingLoader = true;
//呼叫者建立loader,在主執行緒中執行。
LoaderInfo info = createLoader(id, args, callback);
installLoader(info);
return info;
} finally {
mCreatingLoader = false;
}
}
private LoaderInfo createLoader(int id, Bundle args, LoaderManager.LoaderCallbacks<Object> callback) {
LoaderInfo info = new LoaderInfo(id, args, callback);
Loader<Object> loader = callback.onCreateLoader(id, args);
info.mLoader = loader;
return info;
}
void installLoader(LoaderInfo info) {
mLoaders.put(info.mId, info);
//如果已經處於mStarted狀態,說明錯過了doStart方法,那麼只有自己啟動了。
if (mStarted) {
info.start();
}
}
複製程式碼
6.2 restartLoader
的實現
public <D> Loader<D> restartLoader(int id, Bundle args, LoaderManager.LoaderCallbacks<D> callback) {
if (mCreatingLoader) {
throw new IllegalStateException("Called while creating a loader");
}
LoaderInfo info = mLoaders.get(id);
if (DEBUG) Log.v(TAG, "restartLoader in " + this + ": args=" + args);
if (info != null) {
//這個mInactive列表是restartLoader的關鍵。
LoaderInfo inactive = mInactiveLoaders.get(id);
if (inactive != null) {
//如果info已經有了資料,那麼取消它。
if (info.mHaveData) {
if (DEBUG) Log.v(TAG, " Removing last inactive loader: " + info);
inactive.mDeliveredData = false;
inactive.destroy();
info.mLoader.abandon();
mInactiveLoaders.put(id, info);
} else {
//info沒有開始,那麼直接把它移除。
if (!info.mStarted) {
if (DEBUG) Log.v(TAG, " Current loader is stopped; replacing");
mLoaders.put(id, null);
info.destroy();
//info已經開始了。
} else {
//先取消。
info.cancel();
if (info.mPendingLoader != null) {
if (DEBUG) Log.v(TAG, " Removing pending loader: " + info.mPendingLoader);
info.mPendingLoader.destroy();
info.mPendingLoader = null;
}
//inactive && !mHaveData && mStarted,那麼最新的Loader儲存在mPendingLoader這個變數當中。
info.mPendingLoader = createLoader(id, args,
(LoaderManager.LoaderCallbacks<Object>) callback);
return (Loader<D>) info.mPendingLoader.mLoader;
}
}
//如果呼叫restartLoader時已經有了相同id的Loader,那麼儲存在這個列表中進行跟蹤。
} else {
info.mLoader.abandon();
mInactiveLoaders.put(id, info);
}
}
info = createAndInstallLoader(id, args, (LoaderManager.LoaderCallbacks<Object>)callback);
return (Loader<D>) info.mLoader;
}
複製程式碼
程式碼的邏輯比較複雜,我們理一理:
- 在
mLoaders
中不存在相同id
的LoaderInfo
情況下,initLoader
和restartLoader
的行為是一致的。 - 在
mLoaders
中存在相同id
的LoaderInfo
情況下:
initLoader
不會新建LoaderInfo
,也不會改變Bundle
的值,僅僅是替換info.mCallbacks
的例項。restartLoader
除了會新建一個全新的Loader
之外,還會有這麼一套邏輯,它主要和mInactiveLoaders
以及它內部LoaderInfo
所處的狀態有關有關,這個列表用來跟蹤呼叫者希望替換的舊LoaderInfo
:- 如果要被替換的
LoaderInfo
沒有被跟蹤,那麼呼叫info.mLoader.abandon()
,再把它加入到跟蹤列表,然後會新建一個全新的LoaderInfo
放入mLoaders
。 - 如果要替換的
LoaderInfo
還處在被跟蹤的狀態,那麼再去判斷它內部的狀態: - 已經有資料,呼叫
info.destroy()
,info.mLoader.abandon()
,並繼續跟蹤。 - 沒有資料:
- 還沒有開始,呼叫
info.destroy()
,直接在mLoaders
中把對應id
的位置置為null
。 - 已經開始了,那麼先
info.cancel()
,然後把新建的Loader
賦值給LoaderInfo.mPendingLoader
,這時候mLoaders
中就有兩個Loader
了,這是唯一沒有新建LoaderInfo
的情況,即希望替換但是還沒有執行完畢的Loader
以及這個新建立的Loader
。
- 還沒有開始,呼叫
- 如果要被替換的
6.3 destroyLoader
的實現
public void destroyLoader(int id) {
if (mCreatingLoader) {
throw new IllegalStateException("Called while creating a loader");
}
if (DEBUG) Log.v(TAG, "destroyLoader in " + this + " of " + id);
int idx = mLoaders.indexOfKey(id);
if (idx >= 0) {
LoaderInfo info = mLoaders.valueAt(idx);
mLoaders.removeAt(idx);
info.destroy();
}
idx = mInactiveLoaders.indexOfKey(id);
if (idx >= 0) {
LoaderInfo info = mInactiveLoaders.valueAt(idx);
mInactiveLoaders.removeAt(idx);
info.destroy();
}
if (mHost != null && !hasRunningLoaders()) {
mHost.mFragmentManager.startPendingDeferredFragments();
}
}
複製程式碼