Android AsyncTask内部原理

Android AsyncTask内部原理

@(Android)

[toc]

小笔记

基本使用

/**
 * 在主线程中调用,可以做一些初始化的操作,但是不要在这里做耗时操作
 */
@Override
protected void onPreExecute() {
    super.onPreExecute();
}

/**
 * 在子线程中调用,耗时操作全部在这里完成。
 * 如果需要更新进度可以调用 publishProgress(Progress... values)
 */
@Override
protected Object doInBackground(Object[] params) {
    return null;
}

/**
  * 在主线程中调用,显示子线程进度的回调函数
  * @param values
  */
 @Override
 protected void onProgressUpdate(Object[] values) {
     super.onProgressUpdate(values);
 }

/**
  * 在主线程中调用,传入的传输是在doInBackground中返回的值
  * @param o
  */
 @Override
 protected void onPostExecute(Object o) {
     super.onPostExecute(o);
}

/**
 * AsyncTask被取消的时候会回调
 * 参数是从哪里传过来的呢。后面有解释
 */
@Override
protected void onCancelled(Object o) {
    super.onCancelled(o);
    System.out.println(o instanceof Bitmap);
    if (o instanceof Bitmap) {
        image_view.setImageBitmap((Bitmap) o);
    }
}
/**
 * AsyncTask被取消的时候会回调
 */
@Override
protected void onCancelled() {
    super.onCancelled();
    System.out.println("MyAsyncTask ========== onCancelled");
}

了解了基本的使用方法之后,简单的实现一个加载图片的方法吧

package com.example.wen.asynctask;

import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.widget.ImageView;

import java.io.IOException;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;

public class MainActivity extends AppCompatActivity {

    private ImageView image_view;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        image_view = (ImageView) findViewById(R.id.image_view);
        new MyAsyncTask().execute();
    }

    class MyAsyncTask extends AsyncTask {

        /**
         * 在主线程中调用,可以做一些初始化的操作,但是不要在这里做耗时操作
         */
        @Override
        protected void onPreExecute() {
            super.onPreExecute();
        }

        /**
         * 在子线程中调用,耗时操作全部在这里完成。
         * 如果需要更新进度可以调用 publishProgress(Progress... values)
         */
        @Override
        protected Object doInBackground(Object[] params) {

            Bitmap bitmap = null;

            try {
                URL url = new URL("https://www.baidu.com/img/bd_logo1.png");
                HttpURLConnection connection = (HttpURLConnection) url.openConnection();

                bitmap = BitmapFactory.decodeStream(connection.getInputStream());

            } catch (MalformedURLException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }

            return bitmap;
        }

        /**
         * 在主线程中调用,传入的传输是在doInBackground中返回的值
         * @param o
         */
        @Override
        protected void onPostExecute(Object o) {
            super.onPostExecute(o);

            if (o instanceof Bitmap) {
                image_view.setImageBitmap((Bitmap) o);
            }
        }

        /**
         * 在主线程中调用,显示子线程进度的回调函数
         * @param values
         */
        @Override
        protected void onProgressUpdate(Object[] values) {
            super.onProgressUpdate(values);
        }

        /**
         * AsyncTask被取消的时候会回调
         */
        @Override
        protected void onCancelled(Object o) {
            super.onCancelled(o);
            System.out.println(o instanceof Bitmap);
            if (o instanceof Bitmap) {
                image_view.setImageBitmap((Bitmap) o);
            }
        }
        /**
         * AsyncTask被取消的时候会回调
         */
        @Override
        protected void onCancelled() {
            super.onCancelled();
            System.out.println("MyAsyncTask ========== onCancelled");
        }
    }
}

内部实现原理

  1. 在主线程中调用execute(Params... params)方法或者是指定的线程池的executeOnExecutor(Executor exec,Params... params)
 @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;
}

从上面的代码中看到两点:

  1. onPreExecute()方法在主线程中调用的
  2. 另外,在执行exec.execute(mFuture);的时候,会先判断mStatus的状态。所以每一个AsyncTask对象都只能调用execute()方法一次。看一下mStatues的定义:
private volatile Status mStatus = Status.PENDING;

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,【
}

从定义中看到mStatus是用volatile关键字修饰的。volatile的作用是保证操作的可见性,即修改之后其他能马上读取修改后的值。详情看Java 并发编程
  那为什么需要用一个volatile关键字修饰呢。现在有这么一个场景,一个AsyncTask对象已经快执行完后台任务了,准备修改状态Statue.FINISH,但是这个时候,主线程保留了这个AsyncTask对象,并且调用了execute()方法,这个时候就会导致一个AsyncTask被调用了两次。
  而一个AsyncTask不允许执行两次的原因是考虑到了线程安全的问题,如果一个对象被执行了两次,那么就需要考虑自己定义的成员变量的线程安全的问题了。所以直接在new一个出来比执行两次的方式更加方便。

当判断是第一次调用的时候,后面就会调用到exec.execute(mFuture);方法。线程池中的exec.execute()需要一个Runnable的对象,所以让我们看看mFuture的定义吧:

private final FutureTask<Result> mFuture;

我们发现他是一个FutureTask对象。FutrueTask对象需要实现一个方法:

 /**
  * Protected method invoked when this task transitions to state
  * {@code isDone} (whether normally or via cancellation). The
  * default implementation does nothing.  Subclasses may override
  * this method to invoke completion callbacks or perform
  * bookkeeping. Note that you can query status inside the
  * implementation of this method to determine whether this task
  * has been cancelled.
  */
protected void done() { }

并且在FutureTask的构造方法中,需要传一个Callable对象,那么Callable又是一个什么东西呢。简单来说,Callable是一个有返回值的Runnable。所以FutureTask在后台运行的代码就是Callable中的call()的方法。具体来看看在AsyncTask源码中是怎么实现的:

mWorker = new WorkerRunnable<Params, Result>() {
    public Result call() throws Exception {
        mTaskInvoked.set(true);

        Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
        //noinspection unchecked
        Result result = doInBackground(mParams);
        Binder.flushPendingCommands();
        return postResult(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);
        }
    }
};

上面看到的mWorker是一个实现了Callable的类,并且用一个变量保存了在执行AsyncTask时传入的参数

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

上面的代码的大概意思就是在一个子线程中调用了我们实现的doInBackground()方法。在FutureTask中的done()方法中有一个get()方法,作用就是获取doInBackground()返回的数据。然后将返回的数据传到postResult方法中:

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

在这里可以看到AsyncTask的内部是通过Handler来实现的。这里还有一个AsyncTaskResult

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

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

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

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

因为在finish()方法中需要判断Task是否被取消,而Status是对象内部的成员变量,所以需要保留一个AsyncTask对象和在子线程中返回的数据。

当执行完finish()方法之后,基本AsyncTask的内部原理都讲完了。耶!!

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

推荐阅读更多精彩内容