AsyncTask源碼分析

前言

當應用需要執行耗時的任務時,爲了保持應用的平滑流暢和避免ANR,我們需要使用工作線程來執行耗時的任務。當耗時的任務執行完畢時,如果需要更新UI界面,那麼我們需要使用Handler來通知UI線程更新界面。爲了簡化這些操作,方便開發人員編程,Android系統提供了一個AsyncTask類。使用AsyncTask,你可以很方便地執行後臺操作,並在UI線程中更新界面,而無需直接操作Thread和Handler類。

基礎知識

AsyncTask的工作原理主要涉及到了多線程、線程池和Handler消息機制等基礎知識,具體這些基礎知識可以閱讀下面這些文章:

基本用法

AsyncTask的定義如下所示:

public abstract class AsyncTask<Params, Progress, Result> {
    ...
    @MainThread
    protected void onPreExecute() {

    }

    @WorkerThread
    protected abstract Result doInBackground(Params... params);

    @WorkerThread
    protected final void publishProgress(Progress... values) {
        if (!isCancelled()) {
            getHandler().obtainMessage(MESSAGE_POST_PROGRESS, new AsyncTaskResult<Progress>(this, values)).sendToTarget();
        }
    }

    @MainThread
    protected void onProgressUpdate(Progress... values) {

    }

    @MainThread
    protected void onPostExecute(Result result) {

    }

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

可以看到,AsyncTask是一個有3個泛型類型的抽象類。3個泛型類型的說明如下所示:

  1. Params,傳遞給後臺操作的參數的類型。
  2. Progress,後臺操作的進度的類型。
  3. Result,後臺操作的結果的類型。

如果某個泛型沒有用到,那麼可以使用 Void 類型。

爲了使用AsyncTask,首先,我們需要定義一個繼承自它的類,並重寫doInBackground()方法,在 doInBackground() 方法中編寫耗時的後臺操作。如果需要執行一些初始化操作,那麼可以重寫 onPreExecute() 方法。如果需要在界面上更新後臺操作的進度,那麼可以重寫 onProgressUpdate() 方法,並在doInBackground()方法中調用publishProgress()方法發送進度。如果需要在後臺操作結束時更新界面,那麼可以重寫 onPostExecute() 方法。然後,在UI線程中創建一個該類的對象。最後,在UI線程中調用該對象的execute()方法。

示例代碼如下所示:

private class DownloadFilesTask extends AsyncTask<String, Integer, Long> {

    @Override
    protected Long doInBackground(String... urls) {
        int count = urls.length;
        long totalSize = 0;
        for (int i = 0; i < count; i++) {
            totalSize += Downloader.downloadFile(urls[i]);
            publishProgress((int) ((i / (float) count) * 100));
            if (isCancelled()) {
                break;
            }
        }

        return totalSize;
    }

    @Override
    protected void onProgressUpdate(Integer... progress) {
        updateProgress(progress[0]);
    }

    @Override
    protected void onPostExecute(Long result) {
        updateResult(result);
    }
}

// 創建並執行AsyncTask
new DownloadFilesTask().execute(url1, url2, url3);

源碼分析

首先,我們來看AsyncTask的構造方法:

public abstract class AsyncTask<Params, Progress, Result> {
    ...
    public AsyncTask() {
        this((Looper) null);
    }

    public AsyncTask(@Nullable Looper callbackLooper) {
        mHandler = callbackLooper == null || callbackLooper == Looper.getMainLooper()
            ? getMainHandler()
            : new Handler(callbackLooper);
        ...
    }    

    private static Handler getMainHandler() {
        synchronized (AsyncTask.class) {
            if (sHandler == null) {
                sHandler = new InternalHandler(Looper.getMainLooper());
            }
            return sHandler;
        }
    }    
    ...
}

通常,我們會調用AsyncTask無參的構造方法,該方法調用了帶Looper參數的構造方法。此時,callbackLooper參數爲null,AsyncTask會調用getMainHandler()靜態方法來獲取與UI線程相關聯的Handler,並賦值給mHandler成員變量。這樣,當通過mHandler發送消息時,最終會在UI線程中處理髮送的消息。從getMainHandler()靜態方法的代碼可以知道,mHandler是一個InternalHandler類型的Handler對象。我們後面再分析InternalHandler,先接着看AsyncTask的構造方法:

public abstract class AsyncTask<Params, Progress, Result> {
    ...
    public AsyncTask(@Nullable Looper callbackLooper) {
        ...
        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;
            }
        };

        mFuture = new FutureTask<Result>(mWorker) {
            @Override
            protected void done() {
                try {
                    postResultIfNotInvoked(get());
                } catch (InterruptedException e) {
                    android.util.Log.w(LOG_TAG, e);
                } catch (ExecutionException e) {
                    throw new RuntimeException("An error occurred while executing doInBackground()",
                            e.getCause());
                } catch (CancellationException e) {
                    postResultIfNotInvoked(null);
                }
            }
        };
    }    

    private static abstract class WorkerRunnable<Params, Result> implements Callable<Result> {
        Params[] mParams;
    }
    ...
}

AsyncTask的構造方法接着創建了一個WorkerRunnable和一個FutureTask對象,並分別賦值給了mWorker和mFuture成員變量。WorkerRunnable是一個實現了Callable接口的抽象類,當任務被提交給線程池時,call()方法將在線程池的工作線程中執行。FutureTask通常與Callable接口配合使用,當任務正常執行完畢或者被取消時,done()方法將被回調。FutureTask可以管理任務的生命週期,比如,調用get()方法可以獲取任務的執行結果,調用cancel()方法可以取消任務等。

在call()方法中,doInBackground()方法被調用。因此,doInBackground()方法是在工作線程中執行的,我們可以在該方法中執行耗時的後臺操作。當後臺操作執行完畢時,會調用postResult()方法將後臺操作的結果發送出去。在done()方法中,postResultIfNotInvoked()方法被調用,該方法也調用了postResult()方法。done()方法的主要作用是,由於取消任務造成call()方法未被執行時,AsyncTask可以回調onCancelled()方法。我們接着來看postResult()方法:

public abstract class AsyncTask<Params, Progress, Result> {
    ...
    private Result postResult(Result result) {
        Message message = getHandler().obtainMessage(MESSAGE_POST_RESULT,
                new AsyncTaskResult<Result>(this, result));
        message.sendToTarget();
        return result;
    }

    private Handler getHandler() {
        return mHandler;
    }    

    private static class AsyncTaskResult<Data> {
        final AsyncTask mTask;
        final Data[] mData;

        AsyncTaskResult(AsyncTask task, Data... data) {
            mTask = task;
            mData = data;
        }
    }  
    ...
}

postResult()方法調用了getHandler()方法來獲取mHandler對象,然後使用mHandler發送了一條包含了後臺操作結果的消息。這條消息的what字段值爲MESSAGE_POST_RESULT,obj字段爲後臺操作的結果,它是一個AsyncTaskResult對象。前面分析過,mHandler是一個InternalHandler類型的Handler對象。所以,我們接着來看InternalHandler類中處理消息的代碼:

public abstract class AsyncTask<Params, Progress, Result> {
    ...
    private static class InternalHandler extends Handler {
        ...
        @Override
        public void handleMessage(Message msg) {
            AsyncTaskResult<?> result = (AsyncTaskResult<?>) msg.obj;
            switch (msg.what) {
                case MESSAGE_POST_RESULT:
                    result.mTask.finish(result.mData[0]);
                    break;
                ...
            }
        }
    }

    private void finish(Result result) {
        if (isCancelled()) {
            onCancelled(result);
        } else {
            onPostExecute(result);
        }
        mStatus = Status.FINISHED;
    }    
    ...
}

mHandler是一個與UI線程相關聯的Handler對象,所以InternalHandler中的handleMessage()方法是在UI線程中執行的。handleMessage()方法對what字段值爲MESSAGE_POST_RESULT的消息進行了處理,調用了AsyncTask的finish()方法,最終調用了onPostExecute()方法。因此,onPostExecute()方法是在UI線程中執行的,我們可以在該方法中將後臺操作的結果直接更新到界面中。

當我們在doInBackground()方法中執行耗時的後臺操作時,可以調用publishProgress()方法來發送後臺操作的進度。所以,我們接着來看publishProgress()方法:

public abstract class AsyncTask<Params, Progress, Result> {
    ...
    @WorkerThread
    protected final void publishProgress(Progress... values) {
        if (!isCancelled()) {
            getHandler().obtainMessage(MESSAGE_POST_PROGRESS,
                    new AsyncTaskResult<Progress>(this, values)).sendToTarget();
        }
    }

    private static class InternalHandler extends Handler {
        ...
        @Override
        public void handleMessage(Message msg) {
            AsyncTaskResult<?> result = (AsyncTaskResult<?>) msg.obj;
            switch (msg.what) {
                ...
                case MESSAGE_POST_PROGRESS:
                    result.mTask.onProgressUpdate(result.mData);
                    break;
            }
        }
    }    
    ...
}

與postResult()方法類似,publishProgress()方法使用mHandler對象發送了一條包含了後臺操作進度的消息。這條消息的what字段值爲MESSAGE_POST_PROGRESS,obj字段爲後臺操作的進度,它是一個AsyncTaskResult對象。InternalHandler的handleMessage()方法對what字段值爲MESSAGE_POST_PROGRESS的消息進行了處理,調用了AsyncTask的onProgressUpdate()方法。因此,onProgressUpdate()方法是在UI線程中執行的,我們可以在該方法中將後臺操作的進度直接更新到界面中。

然後,我們來看AsyncTask的execute()方法:

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

    @MainThread
    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;
    }    
    ...
}

execute()方法必須在UI線程中調用,它調用了executeOnExecutor()方法。在executeOnExecutor()方法的開始處對AsyncTask的狀態進行了判斷,如果當前狀態不是初始的Status.PENDING狀態,那麼就拋出異常。因此,一個AsyncTask任務只能執行一次。然後,調用了onPreExecute()方法。因此,onPreExecute()方法是在UI線程中執行的,我們可以在該方法中進行一些初始化操作。最後,調用Executor參數的execute()方法將包含了任務的mFuture成員變量提交到sDefaultExecutor中。sDefaultExecutor是一個默認的執行器,它決定了任務將如何執行。所以,我們接着來看sDefaultExecutor相關的代碼:

public abstract class AsyncTask<Params, Progress, Result> {
    ...
    public static final Executor SERIAL_EXECUTOR = new SerialExecutor();

    private static volatile Executor sDefaultExecutor = SERIAL_EXECUTOR;

    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);
            }
        }
    }    
    ...
}

sDefaultExecutor是一個SerialExecutor。當調用execute()方法提交一個任務時,任務將被添加到ArrayDeque隊列的隊尾。如果當前沒有執行中的任務,那麼將調用scheduleNext()方法來取出隊首的一個任務來執行。每個任務執行完畢時也會調用scheduleNext()方法來取出隊首的一個任務來執行。因此,SerialExecutor是一個採用了隊列的串行執行器。所有調用execute()方法執行的AsyncTask都將串行執行。scheduleNext()方法最終將任務提交給了THREAD_POOL_EXECUTOR。所以,我們接着來看THREAD_POOL_EXECUTOR相關的代碼:

public abstract class AsyncTask<Params, Progress, Result> {
    ...
    private static final int CPU_COUNT = Runtime.getRuntime().availableProcessors();
    private static final int CORE_POOL_SIZE = Math.max(2, Math.min(CPU_COUNT - 1, 4));
    private static final int MAXIMUM_POOL_SIZE = CPU_COUNT * 2 + 1;
    private static final int KEEP_ALIVE_SECONDS = 30;

    private static final ThreadFactory sThreadFactory = new ThreadFactory() {
        private final AtomicInteger mCount = new AtomicInteger(1);

        public Thread newThread(Runnable r) {
            return new Thread(r, "AsyncTask #" + mCount.getAndIncrement());
        }
    };

    private static final BlockingQueue<Runnable> sPoolWorkQueue =
            new LinkedBlockingQueue<Runnable>(128);

    public static final Executor THREAD_POOL_EXECUTOR;

    static {
        ThreadPoolExecutor threadPoolExecutor = new ThreadPoolExecutor(
                CORE_POOL_SIZE, MAXIMUM_POOL_SIZE, KEEP_ALIVE_SECONDS, TimeUnit.SECONDS,
                sPoolWorkQueue, sThreadFactory);
        threadPoolExecutor.allowCoreThreadTimeOut(true);
        THREAD_POOL_EXECUTOR = threadPoolExecutor;
    }    
    ...
}

可以看到,THREAD_POOL_EXECUTOR就是一個線程池。因此,AsyncTask中的後臺操作最終是在線程池的工作線程中執行的。如果需要並行地執行AsyncTask,那麼可以調用AsyncTask的executeOnExecutor()方法,並將Executor參數指定爲THREAD_POOL_EXECUTOR線程池或者自定義的線程池。

總結

當執行AsyncTask時,主要會經歷以下4個方法:

  1. onPreExecute(),執行後臺操作之前,在 UI線程 中調用。這個方法通常用於進行一些初始化操作。例如,在UI界面上顯示一個進度條。
  2. doInBackground(Params… params),onPreExecute()方法執行完畢之後,在 工作線程 中調用。這個方法用於執行耗時的後臺操作。AsyncTask的參數被傳遞給這個方法。後臺操作的結果由這個方法返回,並被傳遞給onPostExecute()方法。這個方法中還可以調用publishProgress()方法來發送後臺操作的進度。
  3. onProgressUpdate(Progress… values),調用publishProgress()方法之後,在 UI線程 中調用。這個方法通常用於在UI界面上更新後臺操作的進度。例如,在UI界面上更新一個進度條。publishProgress()方法傳遞的進度作爲參數傳遞給了這個方法。
  4. onPostExecute(Result result),後臺操作完成之後,在 UI線程 中調用。這個方法通常用於在UI界面上更新後臺操作的結果。後臺操作的結果作爲參數傳遞給了這個方法。

最後,AsyncTask應該用於耗時短的操作(最多幾秒鐘)。

參考

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