AsyncTask原理及相關原則

1、AsyncTask類的四個抽象方法

public abstract class AsyncTask<Params, Progress, Result> {

   /**
   Runs on the UI thread before {@link #doInBackground}.
   */
    @MainThread
    protected void onPreExecute() {
    }

   /**
     * Override this method to perform a computation on a background thread. 
     * This method can call {@link #publishProgress} to publish updates
     * on the UI thread.
     **/
    @WorkerThread
    protected abstract Result doInBackground(Params... params);


    /**
     * Runs on the UI thread after {@link #publishProgress} is invoked.
     * The specified values are the values passed to {@link #publishProgress}.
     */
    @SuppressWarnings({"UnusedDeclaration"})
    @MainThread
    protected void onProgressUpdate(Progress... values) {
    }


     /**
     * <p>Runs on the UI thread after {@link #doInBackground}. The
     * specified result is the value returned by {@link #doInBackground}.</p>
     This method won't be invoked if the task was cancelled.</p>
     */
    @SuppressWarnings({"UnusedDeclaration"})
    @MainThread
    protected void onPostExecute(Result result) {
    }

}

2、AsyncTask的執行流程

public final AsyncTask<Params, Progress, Result> execute(Params... params) {
        return executeOnExecutor(sDefaultExecutor, params);
    }

當我們構造一個AsyncTask的子類,並調用其execute方法時,execute方法會調用executeOnExecutor,並向其傳遞一個SERIAL_EXECUTOR和我們execute中的傳遞的參數params。

public final AsyncTask<Params, Progress, Result> executeOnExecutor(Executor exec,
            Params... params) {
        if (mStatus != Status.PENDING) {
            switch (mStatus) {
                case RUNNING:
                    throw new IllegalStateException("Cannot execute task:"
                            + " the task is already running.");
                case FINISHED:
                    throw new IllegalStateException("Cannot execute task:"
                            + " the task has already been executed "
                            + "(a task can be executed only once)");
            }
        }

        mStatus = Status.RUNNING;

        onPreExecute();

        mWorker.mParams = params;
        exec.execute(mFuture);

        return this;
    }

executeOnExecutor中,首先會調用AyncTask中的第一個回調方法onPreExecute,然後將我們的我們的參數params封裝在AsyncTask構建時創建的一個FutureTask中,然後使用SERIAL_EXECUTOR去執行這個FutureTask,

 private static class SerialExecutor implements Executor {
        final ArrayDeque<Runnable> mTasks = new ArrayDeque<Runnable>();
        Runnable mActive;

        public synchronized void execute(final Runnable r) {
            mTasks.offer(new Runnable() {
                public void run() {
                    try {
                        r.run();
                    } finally {
                        scheduleNext();
                    }
                }
            });
            if (mActive == null) {
                scheduleNext();
            }
        }

        protected synchronized void scheduleNext() {
            if ((mActive = mTasks.poll()) != null) {
                THREAD_POOL_EXECUTOR.execute(mActive);
            }
        }
    }

SERIAL_EXECUTOR是負責將所有的FutureTask加入到一個ArrayDeque的隊列中進行排隊,(在FutureTask加入到ArrayDeque之前會構造一個runnable,在這個runnable的run方法中首先會調用FutureTask的run方法,然後在其finally模塊中調用了scheduleNext方法),如果當前沒有一個任務正在運行,就調用scheduleNext從任務隊列ArrayDeque中取出一個任務,使THREAD_POOL_EXECUTOR對這個任務進行執行。

mWorker = new WorkerRunnable<Params, Result>() {
            public Result call() throws Exception {
                mTaskInvoked.set(true);
                Result result = null;
                try {
                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
                    //noinspection unchecked
                    result = doInBackground(mParams);
                    Binder.flushPendingCommands();
                } catch (Throwable tr) {
                    mCancelled.set(true);
                    throw tr;
                } finally {
                    postResult(result);
                }
                return result;
            }
        };

實際上就是調用了FutureTask的run方法,在FutureTask的run方法中又會調用構造它的WorkerRunnable的call方法,在WorkerRunnable的call方法中首先會調用doInBackground方法獲取任務結果,(這個doInBackground是在THREAD_POOL_EXECUTOR執行的,所以可以在裏面做一些耗時操作),然後調用postResult將這個結果發送出去。

private Result postResult(Result result) {
        @SuppressWarnings("unchecked")
        Message message = getHandler().obtainMessage(MESSAGE_POST_RESULT,
                new AsyncTaskResult<Result>(this, result));
        message.sendToTarget();
        return result;
    }

在postResult中,通過一個InternalHandler(InternalHandler在AsyncTask的構造方法中初始化,所以要想消息發送到主線程,AsyncTask必須在主線程中初始化)對result進行封裝,然後發送出去。

private static class InternalHandler extends Handler {
        public InternalHandler(Looper looper) {
            super(looper);
        }

        @SuppressWarnings({"unchecked", "RawUseOfParameterizedType"})
        @Override
        public void handleMessage(Message msg) {
            AsyncTaskResult<?> result = (AsyncTaskResult<?>) msg.obj;
            switch (msg.what) {
                case MESSAGE_POST_RESULT:
                    // There is only one result
                    result.mTask.finish(result.mData[0]);
                    break;
                case MESSAGE_POST_PROGRESS:
                    result.mTask.onProgressUpdate(result.mData);
                    break;
            }
        }
    }

在InternalHandler的handleMessage的result分支中調用了finish方法,在finish方法中,如果任務取消,就調用onCancelled方法,否則調用onPostExecute。
在doInBackground中調用publishProgress發佈進度和結果的發佈類似,都是通過InternalHandler構造一個message,然後將這個message發送到主線程中處理,在InternalHandler的progress分支調用onProgressUpdate。

3、AyncTask中四大原則原因

1、The AsyncTask class must be loaded on the UI thread. This is done
automatically as of android.os.Build.VERSION_CODES#JELLY_BEAN.

2、The task instance must be created on the UI thread.
在AsyncTask中會初始化InternalHandler,如果不是在主線程中,將無法獲取主線程的looper,執行結果也無法發送到主線程。(新版錯誤)
新版初始化InternalHandler的looper是Looper.getMainLooper(),所以InternalHandler中的事件總是在主線程中處理。

正確的回答是execute方法需要在主線程中調用,進而AsyncTask實例需要在主線程中創建。(如果在子線程中創建AsyncTask實例,將無法在主進程中調用execute方法)

3、execute must be invoked on the UI thread.
AsyncTask的execute(Params...)方法必須在UI線程中被調用,原因是在execute(Params...)方法中調用了onPreExecute()方法,onPreExecute()方法是在task開始前在UI線程進行若干準備工作,例如:初始化一個進度條等,所以必須要在UI線程下執行。

4、Do not call onPreExecute()、onPostExecute、doInBackground、onProgressUpdate manually.

5、The task can be executed only once (an exception will be thrown if
a second execution is attempted.)
一個AsyncTask實例只能被執行一次,這是爲了線程安全,當AsyncTask在直接調用executeOnExecutor()方法進入並行模式時,避免同一個任務同時被執行而造成混亂。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章