AsyncTask原理及相关原则

0、AsyncTask

0.1、AsyncTask是什么?
AsyncTask是一个轻量级的异步任务类,它可以在线程池中执行耗时任务,然后把执行的进度和结果发送到主线程中以更新ui。之所以说是轻量级,是因为使用AsyncTask执行的任务是需要排队的,所有并不适合大量耗时操作的执行。

0.2、AsyncTask的构架
两个线程池(SERIAL_EXECUTOR,THREAD_POOL_EXECUTOR)和一个Handler(InternalHandler)构成。

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()方法进入并行模式时,避免同一个任务同时被执行而造成混乱。

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 194,761评论 5 460
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 81,953评论 2 371
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 141,998评论 0 320
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 52,248评论 1 263
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 61,130评论 4 356
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 46,145评论 1 272
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 36,550评论 3 381
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 35,236评论 0 253
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 39,510评论 1 291
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 34,601评论 2 310
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 36,376评论 1 326
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 32,247评论 3 313
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 37,613评论 3 299
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 28,911评论 0 17
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 30,191评论 1 250
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 41,532评论 2 342
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 40,739评论 2 335

推荐阅读更多精彩内容