Loader 知識(shí)梳理(1) - LoaderManager初探

一、概述

剛開(kāi)始學(xué)習(xí)Loader的時(shí)候,只是使用CursorLoader把它當(dāng)作加載封裝在ContentProvider中的數(shù)據(jù)的一種方式,但是如果我們學(xué)會(huì)了如何取定義自己的Loader,那么將不僅僅局限于讀取ContentProvider的數(shù)據(jù),在谷歌的藍(lán)圖框架中,就有一個(gè)分支是介紹如何使用Loader來(lái)實(shí)現(xiàn)數(shù)據(jù)的異步讀?。?/p>

https://github.com/googlesamples/android-architecture/tree/todo-mvp-loaders/

我們現(xiàn)在來(lái)學(xué)習(xí)一下Loader的實(shí)現(xiàn)原理,這將幫助我們知道如何自定義自己的Loader來(lái)進(jìn)行異步數(shù)據(jù)的加載。

二、ActivityLoaderManager的橋梁 - FragmentHostCallback

如果我們把Loader比喻為異步任務(wù)的執(zhí)行者,那么LoaderManager就是這些執(zhí)行者的管理者,而LoaderManager對(duì)于Loader的管理又會(huì)依賴于Activity/Fragment的生命周期。
在整個(gè)系統(tǒng)當(dāng)中,LoaderManagerActivity/Fragment之間的關(guān)系是通過(guò)FragmentHostCallback這個(gè)中介者維系的,當(dāng)Activity或者Fragment的關(guān)鍵生命周期被回調(diào)時(shí),會(huì)調(diào)用FragmentHostCallback的對(duì)應(yīng)方法,它再通過(guò)內(nèi)部持有的LoaderManager實(shí)例來(lái)控制每個(gè)LoaderManager內(nèi)的Loader
FragmentHostCallback當(dāng)中,和Loader有關(guān)的成員變量包括:

    /** 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關(guān)聯(lián)的LoaderManager,每個(gè)Fragment對(duì)應(yīng)一個(gè)LoaderManager
  • mRetainLoadersFragmentLoader是否要保持它們的狀態(tài)。
  • mLoaderManager:和Fragment宿主關(guān)聯(lián)的LoaderManager
  • mCheckedForLoaderManager:當(dāng)Fragment的宿主的LoaderManager被創(chuàng)建以后,該標(biāo)志位變?yōu)?code>true。
  • mLoadersStartedFragment的宿主的Loader是否已經(jīng)啟動(dòng)。

FragmentHostCallbackdoXXXActivity的對(duì)象關(guān)系

下面是整理的表格:

  • restoreLoaderNonConfig <- onCreate
  • reportLoaderStart <- performStart
  • doLoaderStart <- onStart/retainNonConfigurationInstances
  • doLoaderStop(true/false) <- performStop/retainNonConfigurationInstances
  • retainLoaderNonConfig <- retainNonConfigurationInstances
  • doLoaderDestroy <- performDestroy
  • doLoaderRetain <- null

其中有個(gè)函數(shù)比較陌生,retainNonConfigurationInstances,我們看一下它的含義:

    NonConfigurationInstances retainNonConfigurationInstances() {
        Object activity = onRetainNonConfigurationInstance();
        HashMap<String, Object> children = onRetainNonConfigurationChildInstances();
        FragmentManagerNonConfig fragments = mFragments.retainNestedNonConfig();
        
        //由于要求保存loader的狀態(tài),所以我們需要標(biāo)志loader,為此,我們需要在將它交給下個(gè)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;
    }

我們看到,它保存了大量的信息,最后返回一個(gè)NonConfigurationInstances,因此我們猜測(cè)它和onSaveInstance的作用是類似的,在attach方法中,傳入了lastNonConfigurationInstances,之后我們就可以通過(guò)getLastNonConfigurationInstance來(lái)得到它,但是需要注意,這個(gè)變量在performResume之后就會(huì)清空。
通過(guò)ActivityThread的源碼,我們可以看到,這個(gè)方法是在onStoponDestory之間調(diào)用的。

//調(diào)用onStop()
r.activity.performStop(r.mPreserveWindow);
//調(diào)用retainNonConfigurationInstances
r.lastNonConfigurationInstances = r.activity.retainNonConfigurationInstances();
//調(diào)用onDestroy().
mInstrumentation.callActivityOnDestroy(r.activity);

總結(jié)下來(lái),就是一下幾點(diǎn):

  • onStart時(shí)啟動(dòng)Loader
  • onStop時(shí)停止Loader
  • onDestory時(shí)銷毀Loader
  • 在配置發(fā)生變化時(shí)保存Loader

三、LoaderManager/LoaderManagerImpl的含義

通過(guò)上面,我們就可以了解系統(tǒng)是怎么根據(jù)Activity/Fragment的生命周期來(lái)自動(dòng)管理Loader的了,現(xiàn)在,我們來(lái)看一下LoaderManagerImpl的具體實(shí)現(xiàn),這兩個(gè)類的關(guān)系是:

  • LoaderManager:這是一個(gè)抽象類,它內(nèi)部定義了LoaderCallbacks接口,在loader的狀態(tài)發(fā)生改變時(shí)會(huì)通過(guò)這個(gè)回調(diào)通知使用者,此外,它還定義了三個(gè)關(guān)鍵的抽象方法,調(diào)用者只需要使用這三個(gè)方法就能完成數(shù)據(jù)的異步加載。
  • LoaderManagerImpl:繼承于LoaderManager,真正地實(shí)現(xiàn)了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; }
}

這一部分,我們先根據(jù)源碼的注釋對(duì)這些方法有一個(gè)大概的了解:

  • public Loader<D> onCreateLoader(int id, Bundle args)

  • 當(dāng)LoaderManager需要?jiǎng)?chuàng)建一個(gè)Loader時(shí),回調(diào)該函數(shù)來(lái)要求使用者提供一個(gè)Loader,而id為這個(gè)Loader的唯一標(biāo)識(shí)。

  • public void onLoadFinished(Loader<D> loader, D data)

  • 當(dāng)之前創(chuàng)建的Loader完成了任務(wù)之后回調(diào),data就是得到的數(shù)據(jù)。

  • 回調(diào)時(shí),可能Activity已經(jīng)調(diào)用了onSaveInstanceState,因此不建議在其中提交Fragment事務(wù)。

  • 這個(gè)方法會(huì)保證數(shù)據(jù)資源在被釋放之前調(diào)用,例如,當(dāng)使用CursorLoader時(shí),LoaderManager會(huì)負(fù)責(zé)cursor的關(guān)閉。

  • LoaderManager會(huì)主動(dòng)監(jiān)聽(tīng)數(shù)據(jù)的變化。

  • public void onLoaderReset(Loader<D> loader)

  • 當(dāng)先前創(chuàng)建的某個(gè)Loaderreset時(shí)回調(diào)。

  • 調(diào)用者應(yīng)當(dāng)在收到該回調(diào)以后移除與舊Loader有關(guān)的數(shù)據(jù)。

  • public abstract <D> Loader<D> initLoader(int id, Bundle args, LoaderManager.LoaderCallbacks<D> callback)

  • 用來(lái)初始化和激活Loader,args一般用來(lái)放入查詢的條件。

  • 如果id對(duì)應(yīng)的Loader之前不存在,那么會(huì)創(chuàng)建一個(gè)新的,如果此時(shí)Activity/Fragment已經(jīng)處于started狀態(tài),那么會(huì)啟動(dòng)這個(gè)Loader

  • 如果id對(duì)應(yīng)的Loader之前存在,那么會(huì)復(fù)用之前的Loader,并且忽略Bundle參數(shù),它僅僅是使用新的callback。

  • 如果調(diào)用此方法時(shí),滿足2個(gè)條件:調(diào)用者處于started狀態(tài)、Loader已經(jīng)存在并且產(chǎn)生了數(shù)據(jù),那么onLoadFinished會(huì)立刻被回調(diào)。

  • 這個(gè)方法一般來(lái)說(shuō)應(yīng)該在組件被初始化調(diào)用。

  • public abstract <D> Loader<D> restartLoader(int id, Bundle args, LoaderManager.LoaderCallbacks<D> callback)

  • 啟動(dòng)一個(gè)新的Loader或者重新啟動(dòng)一個(gè)舊的Loader,如果此時(shí)Activity/Fragment已經(jīng)處于Started狀態(tài),那么會(huì)開(kāi)始loading過(guò)程。

  • 如果一個(gè)相同idloader之前已經(jīng)存在了,那么當(dāng)新的loader完成工作之后,會(huì)銷毀舊的loader,在舊的Loader已經(jīng)被destroyed之前,會(huì)回調(diào)對(duì)應(yīng)的callback。

  • 因?yàn)?code>initLoader會(huì)忽略Bundle參數(shù),所以當(dāng)我們的查詢需要依賴于bundle內(nèi)的參數(shù)時(shí),那么就需要使用這個(gè)方法。

  • public abstract void destroyLoader(int id)

  • 停止或者移除對(duì)應(yīng)idloader。

  • 如果這個(gè)loader之前已經(jīng)回調(diào)過(guò)了onLoadFinished方法,那么onLoaderReset會(huì)被回調(diào),參數(shù)就是要銷毀的那個(gè)Loader實(shí)例。

  • public abstract <D> Loader<D> getLoader(int id)

  • 返回對(duì)應(yīng)idloader。

  • public boolean hasRunningLoaders()

  • 是否有正在運(yùn)行,但是沒(méi)有返回?cái)?shù)據(jù)的loader。

五、LoaderInfo

LoaderInfo 包裝了 Loader,其中包含了狀態(tài)變量提供給 LoaderManager,并且在構(gòu)造時(shí)候傳入了 LoaderManager.LoaderCallbacks<Object>,這也是回調(diào)給我們調(diào)用者的地方,里面的邏輯很復(fù)雜,我們主要關(guān)注這3個(gè)方法在什么時(shí)候被調(diào)用:

    final class LoaderInfo implements Loader.OnLoadCompleteListener<Object>,
            Loader.OnLoadCanceledListener<Object> {
        final int mId; //唯一標(biāo)識(shí) Loader。
        final Bundle mArgs; //查詢參數(shù)。
        LoaderManager.LoaderCallbacks<Object> mCallbacks; //給調(diào)用者的回調(diào)。
        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中正在恢復(fù)狀態(tài),所以我們什么也不做。
                mStarted = true;
                return;
            }
            if (mStarted) {
                //已經(jīng)開(kāi)始了,那么返回。
                return;
            }
            mStarted = true;
            //如果Loader沒(méi)有創(chuàng)建,那么創(chuàng)建讓用戶去創(chuàng)建它。
            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);
                }
                //注冊(cè)監(jiān)聽(tīng),onLoadCanceled和OnLoadCanceledListener,因?yàn)長(zhǎng)oaderInfo實(shí)現(xiàn)了這兩個(gè)接口,因此把它自己傳進(jìn)去。
                if (!mListenerRegistered) {
                    mLoader.registerListener(mId, this);
                    mLoader.registerOnLoadCanceledListener(this);
                    mListenerRegistered = true;
                }
                //Loader開(kāi)始工作。
                mLoader.startLoading();
            }
        }
        
        //恢復(fù)之前的狀態(tài)。
        void retain() {
            if (DEBUG) Log.v(TAG, "  Retaining: " + this);
            mRetaining = true; //正在恢復(fù)
            mRetainingStarted = mStarted; //恢復(fù)時(shí)的狀態(tài)
            mStarted = false; 
            mCallbacks = null;
        }
        
        //狀態(tài)恢復(fù)完之后調(diào)用。
        void finishRetain() {
            if (mRetaining) {
                if (DEBUG) Log.v(TAG, "  Finished Retaining: " + this);
                mRetaining = false;
                if (mStarted != mRetainingStarted) {
                    if (!mStarted) {
                        //如果在恢復(fù)完后發(fā)現(xiàn),它已經(jīng)不處于Started狀態(tài),那么停止。
                        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() 方法中,如果我們發(fā)現(xiàn) mLoader 沒(méi)有創(chuàng)建,那么通知調(diào)用者創(chuàng)建它。

onLoaderReset:在 destroy() 方法中,也就是Loader被銷毀時(shí)調(diào)用,它的調(diào)用需要滿足以下條件:

  • mHaveData == true:mHaveData 被置為 true 的地方是在 onLoadComplete 中判斷到有新的數(shù)據(jù),并且之前 mHaveData == false,在 onDestroy 時(shí)置為 false。
  • mDeliveredData == true:它在 callOnLoadFinished 時(shí)被置為 true,成功地回調(diào)了調(diào)用者的 onLoadFinished
  • 這兩個(gè)條件一結(jié)合,就可以知道這是一個(gè)已經(jīng)遞交過(guò)數(shù)據(jù)的loader,所以在destory的時(shí)候,就要通知調(diào)用者loader被替換了。

六、LoaderManagerImpl實(shí)現(xiàn)的三個(gè)關(guān)鍵方法

6.1 initLoader的實(shí)現(xiàn)

public <D> Loader<D> initLoader(int id, Bundle args, LoaderManager.LoaderCallbacks<D> callback) {
    //createAndInstallLoader方法正在執(zhí)行,拋出異常。
    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;
    }
    //如果已經(jīng)有數(shù)據(jù),并且處于LoaderManager處于Started狀態(tài),那么立刻返回。
    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; 
        //調(diào)用者創(chuàng)建loader,在主線程中執(zhí)行。       
        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);
    //如果已經(jīng)處于mStarted狀態(tài),說(shuō)明錯(cuò)過(guò)了doStart方法,那么只有自己?jiǎn)?dòng)了。
    if (mStarted) {
        info.start();
    }
}

6.2 restartLoader的實(shí)現(xiàn)

    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) {
            //這個(gè)mInactive列表是restartLoader的關(guān)鍵。
            LoaderInfo inactive = mInactiveLoaders.get(id);
            if (inactive != null) {
                //如果info已經(jīng)有了數(shù)據(jù),那么取消它。
                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沒(méi)有開(kāi)始,那么直接把它移除。
                    if (!info.mStarted) {
                        if (DEBUG) Log.v(TAG, "  Current loader is stopped; replacing");
                        mLoaders.put(id, null);
                        info.destroy();
                    //info已經(jīng)開(kāi)始了。
                    } 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這個(gè)變量當(dāng)中。
                        info.mPendingLoader = createLoader(id, args, 
                                (LoaderManager.LoaderCallbacks<Object>) callback);
                        return (Loader<D>) info.mPendingLoader.mLoader;
                    }
                }
            //如果調(diào)用restartLoader時(shí)已經(jīng)有了相同id的Loader,那么保存在這個(gè)列表中進(jìn)行跟蹤。
            } else {
                info.mLoader.abandon();
                mInactiveLoaders.put(id, info);
            }
        }
        
        info = createAndInstallLoader(id, args,  (LoaderManager.LoaderCallbacks<Object>)callback);
        return (Loader<D>) info.mLoader;
    }

代碼的邏輯比較復(fù)雜,我們理一理:

  • mLoaders中不存在相同idLoaderInfo情況下,initLoaderrestartLoader的行為是一致的。
  • mLoaders中存在相同idLoaderInfo情況下:
  • initLoader不會(huì)新建LoaderInfo,也不會(huì)改變Bundle的值,僅僅是替換info.mCallbacks的實(shí)例。
  • restartLoader除了會(huì)新建一個(gè)全新的Loader之外,還會(huì)有這么一套邏輯,它主要和 mInactiveLoaders以及它內(nèi)部LoaderInfo所處的狀態(tài)有關(guān)有關(guān),這個(gè)列表用來(lái)跟蹤調(diào)用者希望替換的舊LoaderInfo
    • 如果要被替換的LoaderInfo沒(méi)有被跟蹤,那么調(diào)用info.mLoader.abandon(),再把它加入到跟蹤列表,然后會(huì)新建一個(gè)全新的LoaderInfo放入mLoaders
    • 如果要替換的LoaderInfo還處在被跟蹤的狀態(tài),那么再去判斷它內(nèi)部的狀態(tài):
    • 已經(jīng)有數(shù)據(jù),調(diào)用info.destroy(),info.mLoader.abandon(),并繼續(xù)跟蹤。
    • 沒(méi)有數(shù)據(jù):
      • 還沒(méi)有開(kāi)始,調(diào)用info.destroy(),直接在mLoaders中把對(duì)應(yīng)id的位置置為null。
      • 已經(jīng)開(kāi)始了,那么先info.cancel(),然后把新建的Loader賦值給LoaderInfo.mPendingLoader ,這時(shí)候mLoaders中就有兩個(gè)Loader了,這是唯一沒(méi)有新建LoaderInfo的情況,即希望替換但是還沒(méi)有執(zhí)行完畢的Loader以及這個(gè)新創(chuàng)建的Loader

6.3 destroyLoader的實(shí)現(xiàn)

    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();
        }
    }
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書(shū)系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

  • 1 背景## 在Android中任何耗時(shí)的操作都不能放在UI主線程中,所以耗時(shí)的操作都需要使用異步實(shí)現(xiàn)。同樣的,在...
    我是昵稱閱讀 1,336評(píng)論 0 3
  • Android 自定義View的各種姿勢(shì)1 Activity的顯示之ViewRootImpl詳解 Activity...
    passiontim閱讀 178,716評(píng)論 25 709
  • Android開(kāi)發(fā)者都經(jīng)歷過(guò)APP UI開(kāi)發(fā)不當(dāng) 會(huì)造成overDraw,導(dǎo)致APP UI渲染過(guò)慢,但是很多人卻沒(méi)...
    Tamic閱讀 16,194評(píng)論 30 104
  • 明天要跟歐巴一天耗在圖書(shū)館。 剛他問(wèn)我,明天你會(huì)看什么書(shū)呀?我想都不想就回答:育兒方面的書(shū)。 乖乖這么厲害啊。 哈...
    后宮魘閱讀 249評(píng)論 0 0
  • 故鄉(xiāng)的風(fēng)青春的雨,都貌似離我而去了,外面的雨滴落在芒果樹(shù)上的聲音仿佛近在耳邊,一個(gè)姑娘同一個(gè)少年道別的聲音也在此刻...
    青春的雨閱讀 355評(píng)論 1 1

友情鏈接更多精彩內(nèi)容