Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲
 Android教程網 >> Android技術 >> 關於Android編程 >> AsyncTask解析

AsyncTask解析

編輯:關於Android編程

AsyncTask原理簡介

AsyncTask通過Handler實現異步消息處理。 AsyncTask是一個抽象類,使用的時候必須要實現抽象方法doInBackground(Params… params),onPreExecute()和PostExecute(Result result)和onProgressUpdate(Progress… values)都是空方法,當業務需要的時候可以選擇重寫該方法。 AsyncTask初始化流程圖

image

AsyncTask執行流程圖

image
- AsyncTask默認單任務執行模式,同一時間只能有一個任務在執行。

關鍵源碼解析

public abstract class AsyncTask {
    private static final String LOG_TAG = "AsyncTask";

    private static final int CPU_COUNT = Runtime.getRuntime().availableProcessors();
    private static final int CORE_POOL_SIZE = CPU_COUNT + 1;
    private static final int MAXIMUM_POOL_SIZE = CPU_COUNT * 2 + 1;
    private static final int KEEP_ALIVE = 1;

    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 sPoolWorkQueue =
            new LinkedBlockingQueue(128);

    // 線程池,靜態變量,所有的AsyncTask對象共享
    public static final Executor THREAD_POOL_EXECUTOR
            = new ThreadPoolExecutor(CORE_POOL_SIZE, MAXIMUM_POOL_SIZE, KEEP_ALIVE,
            TimeUnit.SECONDS, sPoolWorkQueue, sThreadFactory);

    // 自定義Executor,保證同一時間只有一個任務執行,靜態變量所有的AsyncTask對象共享
    public static final Executor SERIAL_EXECUTOR = new SerialExecutor();
    // 任務完成,消息標志
    private static final int MESSAGE_POST_RESULT = 0x1;
    // 任務進度,消息標志
    private static final int MESSAGE_POST_PROGRESS = 0x2;

    private static volatile Executor sDefaultExecutor = SERIAL_EXECUTOR;
    private static InternalHandler sHandler;

    private final WorkerRunnable mWorker;
    private final FutureTask mFuture;
    // 表示任務當前的狀態
    private volatile Status mStatus = Status.PENDING;

    private final AtomicBoolean mCancelled = new AtomicBoolean();
    private final AtomicBoolean mTaskInvoked = new AtomicBoolean();
    // 自定義Executor,保證同一時間只有一個任務執行
    private static class SerialExecutor implements Executor {
        // 自增長隊列,多線程不安全
        final ArrayDeque mTasks = new ArrayDeque();
        Runnable mActive;
        // 加鎖
        public synchronized void execute(final Runnable r) {
            // 向隊列中插入任務
            mTasks.offer(new Runnable() {
                public void run() {
                    try {
                        r.run();
                    } finally {
                        // 當前任務執行完畢後,執行下一個任務
                        scheduleNext();
                    }
                }
            });
            // mActive為null,代表當前沒有任務執行,執行剛才插入隊列的任務
            if (mActive == null) {
                scheduleNext();
            }
        }

        // 如果隊列中沒有任務,mActive則變為null;有任務則賦值給mActive,線程池來執行該任務
        protected synchronized void scheduleNext() {
            if ((mActive = mTasks.poll()) != null) {
                THREAD_POOL_EXECUTOR.execute(mActive);
            }
        }
    }


    public enum Status {
        // 初始化狀態
        PENDING,
       // 正在運行狀態
        RUNNING,
        // 結束狀態
        FINISHED,
    }

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

    /** @hide */
    public static void setDefaultExecutor(Executor exec) {
        sDefaultExecutor = exec;
    }

   // AsyncTask構造方法
public AsyncTask() {
        // 初始化Callable對象
        mWorker = new WorkerRunnable() {
            public Result call() throws Exception {
                mTaskInvoked.set(true);

                Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
                // 調用doInBackground()方法
                Result result = doInBackground(mParams);
                Binder.flushPendingCommands();
                // 執行完畢發送結果
                return postResult(result);
            }
        };

        // 初始化FutureTask對象,mWorker傳遞進去
        mFuture = new FutureTask(mWorker) {
            @Override
            protected void done() {
                try {
                   //如果mWorker的call()異常未執行,在這邊發送結果
                    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 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(this, result));
        message.sendToTarget();
        return result;
    }


    public final Status getStatus() {
        return mStatus;
    }

    // 需要實現的方法,耗時操作的代碼塊
    protected abstract Result doInBackground(Params... params);

    // 任務開始前的回調方法體
    protected void onPreExecute() {
    }

    // 任務完成後回調方法體
    protected void onPostExecute(Result result) {
    }

    // 進度更新回調方法體
    protected void onProgressUpdate(Progress... values) {
    }

    // 任務取消回調方法體
    protected void onCancelled(Result result) {
        onCancelled();
    }


    protected void onCancelled() {
    }


    public final boolean isCancelled() {
        return mCancelled.get();
    }

    public final boolean cancel(boolean mayInterruptIfRunning) {
        mCancelled.set(true);
        return mFuture.cancel(mayInterruptIfRunning);
    }

    // 獲取任務結果
    public final Result get() throws InterruptedException, ExecutionException {
        return mFuture.get();
    }

    // 獲取任務結果,設置等待結果的超時時間
    public final Result get(long timeout, TimeUnit unit) throws InterruptedException,
            ExecutionException, TimeoutException {
        return mFuture.get(timeout, unit);
    }

    // 開始執行任務,參數最終會傳遞給doInBackground(Params... params)方法
public final AsyncTask execute(Params... params) {
    // sDefaultExecutor默認是SerialExecutor對象,如果不希望同一時間只有一個任務在執行,可以設置sDefaultExecutor為自定義的Executor對象
    return executeOnExecutor(sDefaultExecutor, params);
}

    // 開始執行任務,參數最終會傳遞給doInBackground(Params... params)方法
public final AsyncTask execute(Params... params) {
    // sDefaultExecutor默認是具有單線程池效果的Executor對象(下面會分析該對象源碼),如果不希望同一時間只有一個任務在執行,可以設置sDefaultExecutor為自定義的Executor對象
    return executeOnExecutor(sDefaultExecutor, params);
}

public final AsyncTask executeOnExecutor(Executor exec,
            Params... params) {
        // 如果不是初始狀態,拋出異常。說明一個AsynyTask對象只能調用一次execute(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;
        // 線程池執行FutureTask對象
        exec.execute(mFuture);

        return this;
    }

    // 靜態方法,可以當做單線程池來用
    public static void execute(Runnable runnable) {
        sDefaultExecutor.execute(runnable);
    }

    // 進度更新時,通過Handler發送通知
    protected final void publishProgress(Progress... values) {
        if (!isCancelled()) {
            getHandler().obtainMessage(MESSAGE_POST_PROGRESS,
                    new AsyncTaskResult
  1. 上一頁:
  2. 下一頁:
熱門文章
閱讀排行版
Copyright © Android教程網 All Rights Reserved