AsyncTask源碼分析

首先看AsyncTask的execute

爲啥一個任務實例只能執行一次,如果執行第二次將會拋出異常

看下面的代碼,一共有三種狀態PENDING(尚未執行),RUNNING(執行中),FINISHED(已經執行完),只有是未執行則開始執行,否則是執行中或是已經執行完則拋異常.

       
 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中執行了onPreExecute()方法,說明onPreExecute也運行在主線程中

可以看到mWorker存儲了execute傳過來的參數,mWorker是WorkerRunnable類型的,而WorkerRunnable實現了Callable,

Callable類似於Runnable的接口,都是可被其它線程執行的任務,mWorker在AsyncTask的構造方法裏被初始化,可以看到call裏執行了doInBackground,所以就從主線程執行到了子線程

mWorker.mParams = params;

private final WorkerRunnable<Params, Result> mWorker;

private static abstract class WorkerRunnable<Params, Result> implements Callable<Result> {
        Params[] mParams;
    }
 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;
            }
        };

exec.execute(mFuture);是線程池,每execute一次會從線程池中取出一個線程執行

mFuture的聲明private final FutureTask<Result> mFuture

FutureTask可以用來封裝一個Runnable或者Callable任務,並異步執行,當用戶想要返回的結果時,只需要調用get方法獲取。

FutureTask繼承了RunnableFuture接口,它可以直接作爲一個Runnable或Callable提交到線程池執行。

在下面的初始化中new FutureTask<Result>(mWorker)可以看到保存了mWorker

也就是說exec.execute(mFuture);這句話就是要執行mFuture的run方法,run方法中result = c.call();這句話就調到了mWorker的call方法,然後就執行了doInBackground,然後將doInBackground執行結果保存在result中,run方法中還有句set(result),set中調用了done方法,這個done方法會被調用,就會執行下面的done方法.(加粗字體的是java的知識)

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

然後繼續執行,最後走到result.mTask.onProgressUpdate(result.mData);因此通過handler發消息將結果返回到主線程.執行了onProgressUpdate,如果finish則執行onPostExecute

    private void postResultIfNotInvoked(Result result) {
        final boolean wasTaskInvoked = mTaskInvoked.get();
        if (!wasTaskInvoked) {
            postResult(result);
        }
    }

    private Result postResult(Result result) {
        @SuppressWarnings("unchecked")
        Message message = getHandler().obtainMessage(MESSAGE_POST_RESULT,
                new AsyncTaskResult<Result>(this, result));
        message.sendToTarget();
        return result;
    }       
 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;
            }
        }
    private void finish(Result result) {
        if (isCancelled()) {
            onCancelled(result);
        } else {
            onPostExecute(result);
        }
        mStatus = Status.FINISHED;
    }

值得注意的是AsyncTask三種泛型類型分別代表“啓動任務執行的輸入參數”、“後臺任務執行的進度”、“後臺計算結果的類型”。在特定場合下,並不是所有類型都被使用,如果沒有被使用,可以用java.lang.Void類型代替。

 

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