AsyncTask使用總結(jié)及源碼分析

AsyncTask

AsyncTask是android再API-3中加入的類,為了方便開發(fā)人員執(zhí)行后臺(tái)操作并在UI線程上發(fā)布結(jié)果而無需操作Threads和handlers。AsyncTask的設(shè)計(jì)是圍繞Threads和handlers的一個(gè)輔助類,不構(gòu)成一個(gè)通用的線程框架。其用于時(shí)間較短的網(wǎng)絡(luò)請(qǐng)求,例如登錄請(qǐng)求。對(duì)于下載文件這種長(zhǎng)時(shí)間的網(wǎng)絡(luò)請(qǐng)求并不合適。
?AsyncTask是一個(gè)抽象類,使用時(shí)必須繼承AsyncTask并實(shí)現(xiàn)其protected abstract Result doInBackground(Params... params);方法。在繼承時(shí)可以為AsyncTask類指定三個(gè)泛型參數(shù),這三個(gè)參數(shù)的用途如下:

  1. Params
    在執(zhí)行AsyncTask時(shí)需要傳入的參數(shù),可用于在后臺(tái)任務(wù)中使用。
  2. Progress
    后臺(tái)任何執(zhí)行時(shí),如果需要在界面上顯示當(dāng)前的進(jìn)度,則使用這里指定的泛型作為進(jìn)度單位。
  3. Result
    當(dāng)任務(wù)執(zhí)行完畢后,如果需要對(duì)結(jié)果進(jìn)行返回,則使用這里指定的泛型作為返回值類型。

舉個(gè)例子:

public class MainActivity extends AppCompatActivity{
    private static final String TAG = "MainActivity";
    private ProgressDialog mDialog;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        mDialog = new ProgressDialog(this);
        mDialog.setMax(100);
        mDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
        mDialog.setCancelable(false);

        new myAsycnTask().execute();

    }
    private  class myAsycnTask extends AsyncTask<Void,Integer,Void>{
        @Override
        protected void onPreExecute() {
           //執(zhí)行任務(wù)之前,準(zhǔn)備操作
            super.onPreExecute();
            mDialog.show();
        }

        @Override
        protected Void doInBackground(Void... params) {
            //任務(wù)執(zhí)行過程中 
            for (int i =0 ;i<100;i++)
            {
                SystemClock.sleep(100);
                publishProgress(i);
            }
            return null;
        }
        @Override
        protected void onProgressUpdate(Integer... values) {
           //任務(wù)執(zhí)行過程中更新狀態(tài)
            super.onProgressUpdate(values);
            mDialog.setProgress(values[0]);
        }
        @Override
        protected void onPostExecute(Void aVoid) {
            //任務(wù)執(zhí)行完成之后
            super.onPostExecute(aVoid);
            mDialog.dismiss();
        }
    }
}

AsyncTask 異步加載數(shù)據(jù)可能需要重寫以下幾個(gè)方法:

  1. onPreExecute()
    這個(gè)方法會(huì)在后臺(tái)任務(wù)開始執(zhí)行之間調(diào)用,用于進(jìn)行一些的初始化操作。
  2. doInBackground(Params...)
    子類必須重寫該方法,這個(gè)方法中的所有代碼都會(huì)在子線程中執(zhí)行,處理耗時(shí)任務(wù)。任務(wù)完成后可以通過return語句將結(jié)果返回,如果AsyncTask的第三個(gè)泛型參數(shù)指定的是Void,就可以不返回任務(wù)執(zhí)行結(jié)果。在這個(gè)方法中不可以進(jìn)行UI操作,如果需要更新UI元素,可以調(diào)用publishProgress(Progress...)方法來完成。
  3. onProgressUpdate(Progress...)
    當(dāng)在doInBackground(Params...)中調(diào)用了publishProgress(Progress...)方法后,會(huì)調(diào)用該方法,參數(shù)為后臺(tái)任務(wù)中傳遞過來Progress...。在這個(gè)方法中可以對(duì)UI進(jìn)行操作,利用參數(shù)中的數(shù)值就可以對(duì)UI進(jìn)行相應(yīng)的更新。
  4. onPostExecute(Result)
    當(dāng)后臺(tái)任務(wù)執(zhí)行完畢并通過 return語句進(jìn)行返回時(shí),方法會(huì)被調(diào)用。返回的數(shù)據(jù)會(huì)作為參數(shù)傳遞到此方法中,可以利用返回的數(shù)據(jù)來進(jìn)行一些UI操作。

通過調(diào)用cancel(boolean)方法可以隨時(shí)取消AsyncTask任務(wù),調(diào)用該方法之后會(huì)隨后調(diào)用iscancelled()并返回true,doInBackground(Object[])返回之后會(huì)直接調(diào)用onCancelled(Object)方法而不是正常調(diào)用時(shí)的onPostExecute(Result) 。

注意:

1、AsyncTask必須在UI線程。
?2、必須在UI線程上創(chuàng)建任務(wù)實(shí)例。
?3、execute(Params...) 必須在UI線程中調(diào)用。
?4、不要手動(dòng)調(diào)用onpreexecute(),onpostexecute(Result),doInBackground(Params…),onProgressUpdate(Progress…)這些方法。
?5、任務(wù)只能執(zhí)行一次(如果嘗試執(zhí)行第二次執(zhí)行將拋出異常)。

使用AsyncTask不需要考慮異步消息處理機(jī)制,也不需要考慮UI線程和子線程,只需要調(diào)用一下publishProgress()方法就可以輕松地從子線程切換到UI線程了。從android 3.0之后AsyncTask使用單線程處理所有任務(wù)。

AsyncTask源碼分析

我們使用AsyncTask時(shí),new了一個(gè)myAsycnTask對(duì)象然后執(zhí)行了execute()方法new myAsycnTask().execute(); 。那就先看一下AsyncTask的構(gòu)造函數(shù)和execute()方法:

 /**
     * Creates a new asynchronous task. This constructor must be invoked on the UI thread.
     */
    public AsyncTask() {
        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);
                }
            }
        };
    }
/**
     * Executes the task with the specified parameters. The task returns
     * itself (this) so that the caller can keep a reference to it.
     */
    @MainThread
    public final AsyncTask<Params, Progress, Result> execute(Params... params) {
        return executeOnExecutor(sDefaultExecutor, params);
    }
 private static abstract class WorkerRunnable<Params, Result> implements Callable<Result> {
        Params[] mParams;
    }
/**
     * Creates a {@code FutureTask} that will, upon running, execute the
     * given {@code Callable}.
     */
    public FutureTask(Callable<V> callable) {
        if (callable == null)
            throw new NullPointerException();
        this.callable = callable;
        this.state = NEW;       // ensure visibility of callable
    }

構(gòu)造函數(shù)中初始化了兩個(gè)參數(shù),在mWorker中進(jìn)行了初始化操作,并在初始化mFuture的時(shí)候?qū)?code>mWorker作為參數(shù)傳入。mWorker是一個(gè)實(shí)現(xiàn)了Callable<Result>接口的Callable對(duì)象,mFuture是一個(gè)FutureTask對(duì)象,創(chuàng)建時(shí)設(shè)置了mWorker的回調(diào)方法,然后設(shè)置狀態(tài)為this.state = NEW; (該狀態(tài)是FutureTask類中的) 。

    @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;
    }
  /**
     * Indicates the current status of the task. Each status will be set only once
     * during the lifetime of a task.
     */
    public enum Status {
        /**
         * Indicates that the task has not been executed yet.
         */
        PENDING,
        /**
         * Indicates that the task is running.
         */
        RUNNING,
        /**
         * Indicates that {@link AsyncTask#onPostExecute} has finished.
         */
        FINISHED,
    }

可以看到execute()方法調(diào)用了executeOnExecutor(sDefaultExecutor, params)方法,該方法中,首先檢查當(dāng)前任務(wù)狀態(tài), PENDING,代表任務(wù)還沒有執(zhí)行;RUNNING,代表任務(wù)正在執(zhí)行;FINISHED,代表任務(wù)已經(jīng)執(zhí)行完成。如果任務(wù)沒有執(zhí)行,設(shè)置當(dāng)前狀態(tài)為正在執(zhí)行,調(diào)用了onPreExecute();方法,因此證明了onPreExecute()方法會(huì)第一個(gè)得到執(zhí)行。那doInBackground(Void... params)在什么地方調(diào)用的呢?看方法最后執(zhí)行了exec.execute(mFuture);,這個(gè)exec就是execute(Params... params)中傳過來的sDefaultExecutor參數(shù),讓我們分析一下它做了什么。

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是一個(gè)SerialExecutor對(duì)象,其execute(final Runnable r)方法中的r就是exec.execute(mFuture);中的mFuture,
?SerialExecutor是使用ArrayDeque這個(gè)隊(duì)列來管理Runnable對(duì)象的,如果一次性啟動(dòng)多個(gè)任務(wù),在第一次運(yùn)行execute()方法的時(shí)候,會(huì)調(diào)用ArrayDequeoffer()方法將傳入的Runnable對(duì)象添加到隊(duì)列的尾部,然后判斷mActive對(duì)象是不是等于null,第一次運(yùn)行是等于null的,于是會(huì)調(diào)用scheduleNext()方法。在這個(gè)方法中會(huì)從隊(duì)列的頭部取值,并賦值給mActive對(duì)象,然后調(diào)用THREAD_POOL_EXECUTOR去執(zhí)行取出的取出的Runnable對(duì)象。之后如何又有新的任務(wù)被執(zhí)行,同樣還會(huì)調(diào)用offer()方法將傳入的Runnable添加到隊(duì)列的尾部,但是再去給mActive對(duì)象做非空檢查的時(shí)候就會(huì)發(fā)現(xiàn)mActive對(duì)象已經(jīng)不再是null了,于是就不會(huì)再調(diào)用scheduleNext()方法。
?那么后面添加的任務(wù)豈不是永遠(yuǎn)得不到處理了?當(dāng)然不是,看一看offer()方法里傳入的Runnable匿名類,這里使用了一個(gè)try finally代碼塊,并在finally中調(diào)用了scheduleNext()方法,保證無論發(fā)生什么情況,這個(gè)方法都會(huì)被調(diào)用。也就是說,每次當(dāng)一個(gè)任務(wù)執(zhí)行完畢后,下一個(gè)任務(wù)才會(huì)得到執(zhí)行,SerialExecutor模仿的是單一線程池的效果,如果我們快速地啟動(dòng)了很多任務(wù),同一時(shí)刻只會(huì)有一個(gè)線程正在執(zhí)行,其余的均處于等待狀態(tài)

看看它在子線程里做了什么:

private Callable<V> callable;
ublic FutureTask(Callable<V> callable) {
        if (callable == null)
            throw new NullPointerException();
        this.callable = callable;
        this.state = NEW;       // ensure visibility of callable
    }
public void run() {
        if (state != NEW ||
            !U.compareAndSwapObject(this, RUNNER, null, Thread.currentThread()))
            return;
        try {
            Callable<V> c = callable;
            if (c != null && state == NEW) {
                V result;
                boolean ran;
                try {
                    result = c.call();
                    ran = true;
                } catch (Throwable ex) {
                    result = null;
                    ran = false;
                    setException(ex);
                }
                if (ran)
                    set(result);
            }
        } finally {
            // runner must be non-null until state is settled to
            // prevent concurrent calls to run()
            runner = null;
            // state must be re-read after nulling runner to prevent
            // leaked interrupts
            int s = state;
            if (s >= INTERRUPTING)
                handlePossibleCancellationInterrupt(s);
        }
    }

可以看到mFuture中的run()方法調(diào)用了構(gòu)造函數(shù)中傳過來的callable對(duì)象的call()方法,也就是AsyncTask的構(gòu)造函數(shù)中的mWorkercall()方法,在這個(gè)方法中調(diào)用了result = doInBackground(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;
            }
        };

終于找到了doInBackground()方法的調(diào)用處,雖然經(jīng)過了很多周轉(zhuǎn),但目前的代碼仍然是運(yùn)行在子線程當(dāng)中的,所以這也就是為什么我們可以在doInBackground()方法中去處理耗時(shí)的邏輯。
?call()在最后執(zhí)行了postResult(result);函數(shù),好的,繼續(xù)往下看。

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

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

這段代碼對(duì)是不是很熟悉?這里使用getHandler()返回的sHandler對(duì)象發(fā)出了一條消息,消息中攜帶了MESSAGE_POST_RESULT常量和一個(gè)表示任務(wù)執(zhí)行結(jié)果的AsyncTaskResult對(duì)象。這個(gè)sHandler對(duì)象是InternalHandler類的一個(gè)實(shí)例,那么稍后這條消息肯定會(huì)在InternalHandler的handleMessage()方法中被處理。InternalHandler的源碼如下所示:

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

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

可以看到,根據(jù)不同的消息進(jìn)行了判斷,如果是MESSAGE_POST_RESULT消息則執(zhí)行result.mTask.finish(result.mData[0]);;如果是MESSAGE_POST_PROGRESS則執(zhí)行result.mTask.onProgressUpdate(result.mData);,先讓我們看看AsyncTaskResult<?> result到底是什么?

@SuppressWarnings({"RawUseOfParameterizedType"})
    private static class AsyncTaskResult<Data> {
        final AsyncTask mTask;
        final Data[] mData;

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

可以看到``中包含兩個(gè)參數(shù),一個(gè)是AsyncTask當(dāng)前的AsyncTask對(duì)象,一個(gè)是 Data[]返回?cái)?shù)據(jù)的數(shù)組。所以result.mTask.finish(result.mData[0]);result.mTask.onProgressUpdate(result.mData);就是調(diào)用 AsyncTask的finsh和onProgressUpdate方法。讓我們看一下:

public final boolean cancel(boolean mayInterruptIfRunning) {
        mCancelled.set(true);
        return mFuture.cancel(mayInterruptIfRunning);
    }
 public final boolean isCancelled() {
        return mCancelled.get();
    }
private void finish(Result result) {
        if (isCancelled()) {
            onCancelled(result);
        } else {
            onPostExecute(result);
        }
        mStatus = Status.FINISHED;
    }

就像文章開頭說的,任務(wù)可以隨時(shí)取消,如果取消會(huì)調(diào)用isCancelled()返回true,并且onCancelled(result);會(huì)代替onPostExecute(result);執(zhí)行。如果沒有取消的話就會(huì)直接執(zhí)行onPostExecute(result);方法。
?好了,還剩下publishProgress(Progress...)onProgressUpdate(Progress...)方法了。上面說到sHandler對(duì)象中有兩種消息,還有一種是MESSAGE_POST_PROGRESS執(zhí)行result.mTask.onProgressUpdate(result.mData);方法,讓我們看一下publishProgress(Progress...)

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

非常明確了,在publishProgress(Progress...)方法中發(fā)送了MESSAGE_POST_PROGRESS然后在onProgressUpdate(Progress...)方法中對(duì)消息的數(shù)據(jù)進(jìn)行了處理。正因如此,在doInBackground()方法中調(diào)用publishProgress()方法才可以從子線程切換到UI線程,從而完成對(duì)UI元素的更新操作。
?最后我們看一下取消任務(wù)是怎么實(shí)現(xiàn)的:

//AsycnTask中的cancel方法
public final boolean cancel(boolean mayInterruptIfRunning) {
        mCancelled.set(true);
        return mFuture.cancel(mayInterruptIfRunning);
    }

//mFuture = new FutureTask<Result>(mWorker);類中的cancel方法
    public boolean cancel(boolean mayInterruptIfRunning) {
        if (!(state == NEW &&
              U.compareAndSwapInt(this, STATE, NEW,
                  mayInterruptIfRunning ? INTERRUPTING : CANCELLED)))
            return false;
        try {    // in case call to interrupt throws exception
            if (mayInterruptIfRunning) {
                try {
                    Thread t = runner;
                    if (t != null)
                        t.interrupt();
                } finally { // final state
                    U.putOrderedInt(this, STATE, INTERRUPTED);
                }
            }
        } finally {
            finishCompletion();
        }
        return true;
    }
    private void finishCompletion() {
        // assert state > COMPLETING;
        for (WaitNode q; (q = waiters) != null;) {
            if (U.compareAndSwapObject(this, WAITERS, q, null)) {
                for (;;) {
                    Thread t = q.thread;
                    if (t != null) {
                        q.thread = null;
                        LockSupport.unpark(t);
                    }
                    WaitNode next = q.next;
                    if (next == null)
                        break;
                    q.next = null; // unlink to help gc
                    q = next;
                }
                break;
            }
        }

        done();

        callable = null;        // to reduce footprint
    }

可以看到當(dāng)調(diào)用AsyncTask中的cancel(boolean mayInterruptIfRunning)方法時(shí)會(huì)傳入一個(gè)boolean值,
該值表示是否允許當(dāng)前運(yùn)行中的任務(wù)執(zhí)行完畢,true代表不允許,false代表允許。然后調(diào)用了mFuture.cancel(mayInterruptIfRunning)方法,該方法中會(huì)判斷mayInterruptIfRunning的值,如果為true則調(diào)用線程的interrupt();方法,中斷請(qǐng)求,然后執(zhí)行finishCompletion()方法;如果為false則直接執(zhí)行finishCompletion()方法。finishCompletion()方法將隊(duì)列中的所有等待任務(wù)刪除。

注意:
?AsyncTask不會(huì)不考慮結(jié)果而直接結(jié)束一個(gè)線程。調(diào)用cancel()其實(shí)是給AsyncTask設(shè)置一個(gè)"canceled"狀態(tài)。這取決于你去檢查AsyncTask是否已經(jīng)取消,之后決定是否終止你的操作。對(duì)于mayInterruptIfRunning——它所作的只是向運(yùn)行中的線程發(fā)出interrupt()調(diào)用。在這種情況下,你的線程是不可中斷的,也就不會(huì)終止該線程。
?可以使用isCancelled()判斷任務(wù)是否被取消,然后做相應(yīng)的操作。

參考文獻(xiàn):

http://blog.csdn.net/pi9nc/article/details/12622797
https://developer.android.google.cn/reference/android/os/AsyncTask.html#cancel(boolean)

最后編輯于
?著作權(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)書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

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

  • Android Handler機(jī)制系列文章整體內(nèi)容如下: Android Handler機(jī)制1之ThreadAnd...
    隔壁老李頭閱讀 3,420評(píng)論 1 15
  • 在Android中我們可以通過Thread+Handler實(shí)現(xiàn)多線程通信,一種經(jīng)典的使用場(chǎng)景是:在新線程中進(jìn)行耗時(shí)...
    呂侯爺閱讀 2,175評(píng)論 2 23
  • AsyncTask簡(jiǎn)單介紹 大家應(yīng)該都知道AsyncTask這個(gè)類,也應(yīng)該或多或少都接觸過這個(gè)類,它可以幫我們完成...
    Gzw丶南山閱讀 402評(píng)論 4 0
  • Android開發(fā)者:你真的會(huì)用AsyncTask嗎? 導(dǎo)讀.1 在Android應(yīng)用開發(fā)中,我們需要時(shí)刻注意保證...
    cxm11閱讀 2,773評(píng)論 0 29
  • 簡(jiǎn)介 當(dāng)android應(yīng)用啟動(dòng)的時(shí)候會(huì)啟動(dòng)一條主線程,這個(gè)主線程負(fù)責(zé)向UI組件分發(fā)事件(包括繪制事件),所以當(dāng)在主...
    lee小杰閱讀 666評(píng)論 0 3

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