Android Loader原始碼分析(二)

weixin_33918357發表於2017-08-18

Android Loader原始碼分析(一)中說道在start方法的最後,會呼叫mLoader.startLoading();
startLoading方法又會呼叫onStartLoading方法

//在Loader.java檔案中
public final void startLoading() {
    mStarted = true;
    mReset = false;
    mAbandoned = false;
    onStartLoading();
}
  
//在CursorLoader.java 檔案中
@Override
protected void onStartLoading() {
    if (mCursor != null) {
        deliverResult(mCursor);
    }
    if (takeContentChanged() || mCursor == null) {
        forceLoad();
    }
}
  
public void forceLoad() {
    onForceLoad();
}

在資料還未載入時,mCursor為null,此時會執行forceLoad()
forceLoad()會執行onForceLoad(),此方法的實現是在AsyncTaskLoader.java中

@Override
protected void onForceLoad() {
    super.onForceLoad();
    cancelLoad();
    mTask = new LoadTask();
    if (DEBUG) Log.v(TAG, "Preparing load: mTask=" + mTask);
    executePendingTask();
}

(1)、forceLoad()會呼叫onForceLoad()。而onForceLoad()中會新建LoadTask物件,然後執行executePendingTask()
(2)、在executePendingTask()中會呼叫LoadTask物件的executeOnExecutor()

void executePendingTask() {
    if (mCancellingTask == null && mTask != null) {
        if (mTask.waiting) {
            mTask.waiting = false;
            mHandler.removeCallbacks(mTask);
        }
        if (mUpdateThrottle > 0) {
            long now = SystemClock.uptimeMillis();
            if (now < (mLastLoadCompleteTime+mUpdateThrottle)) {
                // Not yet time to do another load.
                mTask.waiting = true;
                mHandler.postAtTime(mTask, mLastLoadCompleteTime+mUpdateThrottle);
                return;
            }
        }
        mTask.executeOnExecutor(mExecutor, (Void[]) null);
    }
}
  
//LoadTask的實現
final class LoadTask extends AsyncTask<Void, Void, D> implements Runnable {
    private final CountDownLatch mDone = new CountDownLatch(1);
 
    boolean waiting;
 
    /* Runs on a worker thread */
    @Override
    protected D doInBackground(Void... params) {
        try {
            D data = AsyncTaskLoader.this.onLoadInBackground();
            return data;
        } catch (OperationCanceledException ex) {
            if (!isCancelled()) {
                throw ex;
            }
            return null;
        }
    }
 
    /* Runs on the UI thread */
    @Override
    protected void onPostExecute(D data) {
        try {
            AsyncTaskLoader.this.dispatchOnLoadComplete(this, data);
        } finally {
            mDone.countDown();
        }
    }
 
    /* Runs on the UI thread */
    @Override
    protected void onCancelled(D data) {
        try {
            AsyncTaskLoader.this.dispatchOnCancelled(this, data);
        } finally {
            mDone.countDown();
        }
    }
 
    /* Runs on the UI thread, when the waiting task is posted to a handler.
     * This method is only executed when task execution was deferred (waiting was true). */
    @Override
    public void run() {
        waiting = false;
        AsyncTaskLoader.this.executePendingTask();
    }
 
    /* Used for testing purposes to wait for the task to complete. */
    public void waitForLoader() {
        try {
            mDone.await();
        } catch (InterruptedException e) {
            // Ignore
        }
    }
}
  1. LoadTask是AsyncTaskLoader的內部類。實際上,它是AsyncTask的子類,executeOnExecutor()會將任務提交到執行緒池中去執行;
  2. 這個被提交到執行緒池的任務會執行AsyncTask的doInBackground()。
  3. LoadTask的doInBackground()會呼叫onLoadInBackground()
  4. onLoadInBackground()方法會呼叫loadInBackground() 這個方法是在CursorLoader中實現的
/* Runs on a worker thread */
@Override
public Cursor loadInBackground() {
    synchronized (this) {
        if (isLoadInBackgroundCanceled()) {
            throw new OperationCanceledException();
        }
        mCancellationSignal = new CancellationSignal();
    }
    try {
        Cursor cursor = getContext().getContentResolver().query(mUri, mProjection, mSelection,
                mSelectionArgs, mSortOrder, mCancellationSignal);
        if (cursor != null) {
            try {
                // Ensure the cursor window is filled.
                cursor.getCount();
                cursor.registerContentObserver(mObserver);
            } catch (RuntimeException ex) {
                cursor.close();
                throw ex;
            }
        }
        return cursor;
    } finally {
        synchronized (this) {
            mCancellationSignal = null;
        }
    }
}
  1. 當AsyncTask中的任務執行完時,會通過onPostExecute()反饋執行結果。
  2. onPostExecute()會執行dispatchOnLoadComplete(),而後者會呼叫deliverResult()來分發訊息。
  3. 最終會執行mListener.onLoadComplete()。mListener是什麼呢?它是我們在執行LoaderManager.java的start()函式時,通過mLoader.registerListener(mId, this)註冊到Loader上的。也就是說,mListener是LoaderManager中的LoaderInfo物件。

相關文章