本篇文章的主要内容如下:
我们都知道,Android UI线程是不安全的,如果想要在子线程里面进行UI操作,就需要直接Android的异步消息处理机制,前面我写了很多文章从源码层面分析了Android异步消息Handler的处理机制。感兴趣的可以去了解下。不过为了更方便我们在子线程中更新UI元素,Android1.5版本就引入了一个AsyncTask类,使用它就可以非常灵活方便地从子线程切换到UI线程。
AsyncTask是一个抽象类,我们需要创建子类去继承它,并且重写一些方法。AsyncTask接受三个泛型的参数:
除了指定泛型参数,还需要根据重写一些方法,常用的如下:
源码注释如下:
/**
* <p>AsyncTask enables proper and easy use of the UI thread. This class allows you
* to perform background operations and publish results on the UI thread without
* having to manipulate threads and/or handlers.</p>
*
* <p>AsyncTask is designed to be a helper class around {@link Thread} and {@link Handler}
* and does not constitute a generic threading framework. AsyncTasks should ideally be
* used for short operations (a few seconds at the most.) If you need to keep threads
* running for long periods of time, it is highly recommended you use the various APIs
* provided by the <code>java.util.concurrent</code> package such as {@link Executor},
* {@link ThreadPoolExecutor} and {@link FutureTask}.</p>
*
* <p>An asynchronous task is defined by a computation that runs on a background thread and
* whose result is published on the UI thread. An asynchronous task is defined by 3 generic
* types, called <code>Params</code>, <code>Progress</code> and <code>Result</code>,
* and 4 steps, called <code>onPreExecute</code>, <code>doInBackground</code>,
* <code>onProgressUpdate</code> and <code>onPostExecute</code>.</p>
*
* <div class="special reference">
* <h3>Developer Guides</h3>
* <p>For more information about using tasks and threads, read the
* <a href="{@docRoot}guide/components/processes-and-threads.html">Processes and
* Threads</a> developer guide.</p>
* </div>
*
* <h2>Usage</h2>
* <p>AsyncTask must be subclassed to be used. The subclass will override at least
* one method ({@link #doInBackground}), and most often will override a
* second one ({@link #onPostExecute}.)</p>
*
* <p>Here is an example of subclassing:</p>
* <pre class="prettyprint">
* private class DownloadFilesTask extends AsyncTask<URL, Integer, Long> {
* protected Long doInBackground(URL... urls) {
* int count = urls.length;
* long totalSize = 0;
* for (int i = 0; i < count; i++) {
* totalSize += Downloader.downloadFile(urls[i]);
* publishProgress((int) ((i / (float) count) * 100));
* // Escape early if cancel() is called
* if (isCancelled()) break;
* }
* return totalSize;
* }
*
* protected void onProgressUpdate(Integer... progress) {
* setProgressPercent(progress[0]);
* }
*
* protected void onPostExecute(Long result) {
* showDialog("Downloaded " + result + " bytes");
* }
* }
* </pre>
*
* <p>Once created, a task is executed very simply:</p>
* <pre class="prettyprint">
* new DownloadFilesTask().execute(url1, url2, url3);
* </pre>
*
* <h2>AsyncTask's generic types</h2>
* <p>The three types used by an asynchronous task are the following:</p>
* <ol>
* <li><code>Params</code>, the type of the parameters sent to the task upon
* execution.</li>
* <li><code>Progress</code>, the type of the progress units published during
* the background computation.</li>
* <li><code>Result</code>, the type of the result of the background
* computation.</li>
* </ol>
* <p>Not all types are always used by an asynchronous task. To mark a type as unused,
* simply use the type {@link Void}:</p>
* <pre>
* private class MyTask extends AsyncTask<Void, Void, Void> { ... }
* </pre>
*
* <h2>The 4 steps</h2>
* <p>When an asynchronous task is executed, the task goes through 4 steps:</p>
* <ol>
* <li>{@link #onPreExecute()}, invoked on the UI thread before the task
* is executed. This step is normally used to setup the task, for instance by
* showing a progress bar in the user interface.</li>
* <li>{@link #doInBackground}, invoked on the background thread
* immediately after {@link #onPreExecute()} finishes executing. This step is used
* to perform background computation that can take a long time. The parameters
* of the asynchronous task are passed to this step. The result of the computation must
* be returned by this step and will be passed back to the last step. This step
* can also use {@link #publishProgress} to publish one or more units
* of progress. These values are published on the UI thread, in the
* {@link #onProgressUpdate} step.</li>
* <li>{@link #onProgressUpdate}, invoked on the UI thread after a
* call to {@link #publishProgress}. The timing of the execution is
* undefined. This method is used to display any form of progress in the user
* interface while the background computation is still executing. For instance,
* it can be used to animate a progress bar or show logs in a text field.</li>
* <li>{@link #onPostExecute}, invoked on the UI thread after the background
* computation finishes. The result of the background computation is passed to
* this step as a parameter.</li>
* </ol>
*
* <h2>Cancelling a task</h2>
* <p>A task can be cancelled at any time by invoking {@link #cancel(boolean)}. Invoking
* this method will cause subsequent calls to {@link #isCancelled()} to return true.
* After invoking this method, {@link #onCancelled(Object)}, instead of
* {@link #onPostExecute(Object)} will be invoked after {@link #doInBackground(Object[])}
* returns. To ensure that a task is cancelled as quickly as possible, you should always
* check the return value of {@link #isCancelled()} periodically from
* {@link #doInBackground(Object[])}, if possible (inside a loop for instance.)</p>
*
* <h2>Threading rules</h2>
* <p>There are a few threading rules that must be followed for this class to
* work properly:</p>
* <ul>
* <li>The AsyncTask class must be loaded on the UI thread. This is done
* automatically as of {@link android.os.Build.VERSION_CODES#JELLY_BEAN}.</li>
* <li>The task instance must be created on the UI thread.</li>
* <li>{@link #execute} must be invoked on the UI thread.</li>
* <li>Do not call {@link #onPreExecute()}, {@link #onPostExecute},
* {@link #doInBackground}, {@link #onProgressUpdate} manually.</li>
* <li>The task can be executed only once (an exception will be thrown if
* a second execution is attempted.)</li>
* </ul>
*
* <h2>Memory observability</h2>
* <p>AsyncTask guarantees that all callback calls are synchronized in such a way that the following
* operations are safe without explicit synchronizations.</p>
* <ul>
* <li>Set member fields in the constructor or {@link #onPreExecute}, and refer to them
* in {@link #doInBackground}.
* <li>Set member fields in {@link #doInBackground}, and refer to them in
* {@link #onProgressUpdate} and {@link #onPostExecute}.
* </ul>
*
* <h2>Order of execution</h2>
* <p>When first introduced, AsyncTasks were executed serially on a single background
* thread. Starting with {@link android.os.Build.VERSION_CODES#DONUT}, this was changed
* to a pool of threads allowing multiple tasks to operate in parallel. Starting with
* {@link android.os.Build.VERSION_CODES#HONEYCOMB}, tasks are executed on a single
* thread to avoid common application errors caused by parallel execution.</p>
* <p>If you truly want parallel execution, you can invoke
* {@link #executeOnExecutor(java.util.concurrent.Executor, Object[])} with
* {@link #THREAD_POOL_EXECUTOR}.</p>
*/
简单翻译一下:
private class DownloadFilesTask extends AsyncTask<URL, >Integer, Long> { protected Long doInBackground(URL... urls) { int count = urls.length; long totalSize = 0; for (int i = 0; i < count; i++) { totalSize += Downloader.downloadFile(urls[i]); publishProgress((int) ((i / (float) count) * 100)); // Escape early if cancel() is called if (isCancelled()) break; } return totalSize; } protected void onProgressUpdate(Integer... progress) { setProgressPercent(progress[0]); } protected void onPostExecute(Long result) { showDialog("Downloaded " + result + " bytes"); } } 一旦创建,任务会被很轻松的执行。就像下面这块代码一样 new DownloadFilesTask().execute(url1,url2,url3);
private class MyTask extends AsyncTask<Void, Void, Void>{...}
至此这个类的注释翻译完毕,好长啊,大家看完翻译,是不是发现了很多之前没有考虑到的问题。
AsyncTask的结构如下:
AsyncTask的结构.png
我们看到在AsyncTask有4个自定义类,一个枚举类,一个静态块,然后才是这个类的具体变量和属性,那我们就依次讲解
代码在AsyncTask.java 256行
/**
* 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,
}
枚举Status上的注释翻译一下就是:
Status表示当前任务的状态,每种状态只能在任务的生命周期内设置一次。
所以任务有三种状态
代码在AsyncTask.java 656行
private static class InternalHandler extends Handler {
public InternalHandler() {
// 这个handler是关联到主线程的
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;
}
}
}
通过上面的代码我们知道:
通过这段代码我们可以推测AsyncTask内部实现线程切换,即切换到主线程是通过Handler来实现的。
代码在AsyncTask.java 682行
@SuppressWarnings({"RawUseOfParameterizedType"})
private static class AsyncTaskResult<Data> {
final AsyncTask mTask;
final Data[] mData;
AsyncTaskResult(AsyncTask task, Data... data) {
mTask = task;
mData = data;
}
}
通过类名,我们大概可以推测出这一个负责AsyncTask结果的类
AsyncTaskResult这个类 有两个成员变量,一个是AsyncTask一个是泛型的数组。
代码在AsyncTask.java 677行
private static abstract class WorkerRunnable<Params, Result> implements Callable<Result> {
Params[] mParams;
}
这个抽象类很简答,首先是实现了Callable接口,然后里面有个变量 mParams,类型是泛型传进来的数组
AsyncTask的局部变量如下:
private static final String LOG_TAG = "AsyncTask";
private static final int CPU_COUNT = Runtime.getRuntime().availableProcessors();
// We want at least 2 threads and at most 4 threads in the core pool,
// preferring to have 1 less than the CPU count to avoid saturating
// the CPU with background work
private static final int CORE_POOL_SIZE = Math.max(2, Math.min(CPU_COUNT - 1, 4));
private static final int MAXIMUM_POOL_SIZE = CPU_COUNT * 2 + 1;
private static final int KEEP_ALIVE_SECONDS = 30;
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<Runnable> sPoolWorkQueue =
new LinkedBlockingQueue<Runnable>(128);
/**
* An {@link Executor} that can be used to execute tasks in parallel.
*/
public static final Executor THREAD_POOL_EXECUTOR;
/**
* An {@link Executor} that executes tasks one at a time in serial
* order. This serialization is global to a particular process.
*/
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<Params, Result> mWorker;
private final FutureTask<Result> mFuture;
private volatile Status mStatus = Status.PENDING;
private final AtomicBoolean mCancelled = new AtomicBoolean();
private final AtomicBoolean mTaskInvoked = new AtomicBoolean();
那我们就来一一解答
代码在AsyncTask.java 226行
static {
ThreadPoolExecutor threadPoolExecutor = new ThreadPoolExecutor(
CORE_POOL_SIZE, MAXIMUM_POOL_SIZE, KEEP_ALIVE_SECONDS, TimeUnit.SECONDS,
sPoolWorkQueue, sThreadFactory);
threadPoolExecutor.allowCoreThreadTimeOut(true);
THREAD_POOL_EXECUTOR = threadPoolExecutor;
}
通过上面的(七)、局部变量详解,我们知道在静态代码块中创建了一个线程池threadPoolExecutor,并设置了核心线程会超时关闭,最后并把这个线程池指向THREAD_POOL_EXECUTOR。
代码在AsyncTask.java 226行
private static class SerialExecutor implements Executor {
// 循环数组实现的双向Queue,大小是2的倍数,默认是16,有队头和队尾巴两个下标
final ArrayDeque<Runnable> mTasks = new ArrayDeque<Runnable>();
// 正在运行runnable
Runnable mActive;
public synchronized void execute(final Runnable r) {
// 添加到双向队列中去
mTasks.offer(new Runnable() {
public void run() {
try {
//执行run方法
r.run();
} finally {
//无论执行结果如何都会取出下一个任务执行
scheduleNext();
}
}
});
// 如果没有活动的runnable,则从双端队列里面取出一个runnable放到线程池中运行
// 第一个请求任务过来的时候mActive是空的
if (mActive == null) {
//取出下一个任务来
scheduleNext();
}
}
protected synchronized void scheduleNext() {
//从双端队列中取出一个任务
if ((mActive = mTasks.poll()) != null) {
//线线程池执行取出来的任务,真正的执行任务
THREAD_POOL_EXECUTOR.execute(mActive);
}
}
}
PS:scheduleNext()方法是synchronized,所以也是同步的
重点补充:
在Android 3.0 之前是并没有SerialExecutor这个类的,那个时候是直接在AsyncTask中构建一个sExecutor常量,并对线程池总大小,同一时刻能够运行的线程数做了规定,代码如下:
private static final ThreadPoolExecutor sExecutor = new ThreadPoolExecutor(CORE_POOL_SIZE,
MAXIMUM_POOL_SIZE, KEEP_ALIVE, TimeUnit.SECONDS, sWorkQueue, sThreadFactory);
代码如下:
/**
* 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
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);
}
}
};
}
通过注释我们知道,这个方法创建一个异步任务,构造函数必须在UI线程调用
这里面设计了两个概念Callable和FutureTask,如果大家对这两个类有疑问,可以看我上一篇文章Android Handler机制12之Callable、Future和FutureTask
构造函数也比较简单,主要就是给mWorker和mFuture初始化,其中WorkerRunnable实现了Callable接口,
在构造函数里面调用了postResult(Result)和postResultIfNotInvoked(Result),那我们就来分别看下
// doInBackground执行完毕,发送消息
private Result postResult(Result result) {
@SuppressWarnings("unchecked")
// 获取一个Message对象
Message message = getHandler().obtainMessage(MESSAGE_POST_RESULT,
new AsyncTaskResult<Result>(this, result));
// 发送给线程
message.sendToTarget();
return result;
}
通过代码我们知道
这里面调用了 getHandler(),那我们来看下这个方法是怎么写的
private static Handler getHandler() {
synchronized (AsyncTask.class) {
if (sHandler == null) {
sHandler = new InternalHandler();
}
return sHandler;
}
}
我们看到返回的是InternalHandler对象,上面说过了InternalHandler其实是关联主线程的,所以上面方法 message.sendToTarget(); 其实是把消息发送给主线程。
大家注意一下 这里的Message的what值为MESSAGE_POST_RESULT,我们来看下InternalHandler遇到InternalHandler这种消息是怎么处理的
private static class InternalHandler extends Handler {
...
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;
...
}
}
}
我们看到MESSAGE_POST_RESULT对应的是指是执行AsyncTask的finish(Result)方法,所以我们可以这样说,无论AsyncTask是成功了还是失败了,最后都会执行finish(Result)方法。那我们来看下finish(Result)方法里面都干了什么?
private void finish(Result result) {
if (isCancelled()) {
// 如果消息取消了,执行onCancelled方法
onCancelled(result);
} else {
// 如果消息没有取消,则执行onPostExecute方法
onPostExecute(result);
}
// 设置状态值
mStatus = Status.FINISHED;
}
注释写的很清楚了,我这里就不说明了,通过上面的代码和finish方法的分析,我们知道无论成功还是失败,最后一定会调用finish(Result)方法,所以最后状态的值为FINISHED。
private void postResultIfNotInvoked(Result result) {
// 获取mTaskInvoked的值
final boolean wasTaskInvoked = mTaskInvoked.get();
if (!wasTaskInvoked) {
postResult(result);
}
}
通过上面代码我们知道,如果mTaskInvoked不为true,则执行postResult,但是在mWorker初始化的时候为true,除非在没有执行call方法时候,如果没有执行call,说明这个异步线程还没有开始执行,这个时候mTaskInvoked为false。而这时候调用postResultIfNotInvoked则还是会执行postResult(Result),这样保证了AsyncTask一定有返回值。
/**
* Runs on the UI thread before {@link #doInBackground}.
*
* @see #onPostExecute
* @see #doInBackground
*/
// 在调用doInBackground()方法之前,跑在主线程上
@MainThread
protected void onPreExecute() {
}
其实注释很清楚了,在task任务开始执行的时候在主线程调用,在doInBackground(Params… params) 方法之前调用。
/**
* Executes the task with the specified parameters. The task returns
* itself (this) so that the caller can keep a reference to it.
*
* <p>Note: this function schedules the task on a queue for a single background
* thread or pool of threads depending on the platform version. When first
* introduced, AsyncTasks were executed serially on a single background thread.
* Starting with {@link android.os.Build.VERSION_CODES#DONUT}, this was changed
* to a pool of threads allowing multiple tasks to operate in parallel. Starting
* {@link android.os.Build.VERSION_CODES#HONEYCOMB}, tasks are back to being
* executed on a single thread to avoid common application errors caused
* by parallel execution. If you truly want parallel execution, you can use
* the {@link #executeOnExecutor} version of this method
* with {@link #THREAD_POOL_EXECUTOR}; however, see commentary there for warnings
* on its use.
*
* <p>This method must be invoked on the UI thread.
*
* @param params The parameters of the task.
*
* @return This instance of AsyncTask.
*
* @throws IllegalStateException If {@link #getStatus()} returns either
* {@link AsyncTask.Status#RUNNING} or {@link AsyncTask.Status#FINISHED}.
*
* @see #executeOnExecutor(java.util.concurrent.Executor, Object[])
* @see #execute(Runnable)
*/
@MainThread
public final AsyncTask<Params, Progress, Result> execute(Params... params) {
return executeOnExecutor(sDefaultExecutor, params);
}
首先来翻译一下注释
通过代码我们看到,它的内部其实是调用executeOnExecutor(Executor exec, Params... params)方法,只不过第一个参数传入的是sDefaultExecutor,而sDefaultExecutor是SerialExecutor的对象。上面我们提到了SerialExecutor里面利用ArrayDeque来实现串行的,所以我们可以推测出如果在executeOnExecutor(Executor exec, Params... params)方法里面如果第一个参数是自定义的Executor,AsyncTask就可以实现并发执行。
/**
* Executes the task with the specified parameters. The task returns
* itself (this) so that the caller can keep a reference to it.
*
* <p>This method is typically used with {@link #THREAD_POOL_EXECUTOR} to
* allow multiple tasks to run in parallel on a pool of threads managed by
* AsyncTask, however you can also use your own {@link Executor} for custom
* behavior.
*
* <p><em>Warning:</em> Allowing multiple tasks to run in parallel from
* a thread pool is generally <em>not</em> what one wants, because the order
* of their operation is not defined. For example, if these tasks are used
* to modify any state in common (such as writing a file due to a button click),
* there are no guarantees on the order of the modifications.
* Without careful work it is possible in rare cases for the newer version
* of the data to be over-written by an older one, leading to obscure data
* loss and stability issues. Such changes are best
* executed in serial; to guarantee such work is serialized regardless of
* platform version you can use this function with {@link #SERIAL_EXECUTOR}.
*
* <p>This method must be invoked on the UI thread.
*
* @param exec The executor to use. {@link #THREAD_POOL_EXECUTOR} is available as a
* convenient process-wide thread pool for tasks that are loosely coupled.
* @param params The parameters of the task.
*
* @return This instance of AsyncTask.
*
* @throws IllegalStateException If {@link #getStatus()} returns either
* {@link AsyncTask.Status#RUNNING} or {@link AsyncTask.Status#FINISHED}.
*
* @see #execute(Object[])
*/
@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是先执行,并且在UI线程
onPreExecute();
// 设置参数
mWorker.mParams = params;
// 开启了后台线程去计算,这是真正调用doInBackground的地方
exec.execute(mFuture);
// 接着会有onProgressUpdate会被调用,最后是onPostExecute
return this;
}
老规矩 先翻译一下注释:
那我们来看下一下代码,代码里面的逻辑如下:
PS:mFuture和mWorker都是在AsyncTask的构造方法中初始化过的。
主要是设置后台进度,onProgressUpdate会被调用
/**
* This method can be invoked from {@link #doInBackground} to
* publish updates on the UI thread while the background computation is
* still running. Each call to this method will trigger the execution of
* {@link #onProgressUpdate} on the UI thread.
*
* {@link #onProgressUpdate} will not be called if the task has been
* canceled.
*
* @param values The progress values to update the UI with.
*
* @see #onProgressUpdate
* @see #doInBackground
*/
@WorkerThread
protected final void publishProgress(Progress... values) {
if (!isCancelled()) {
getHandler().obtainMessage(MESSAGE_POST_PROGRESS,
new AsyncTaskResult<Progress>(this, values)).sendToTarget();
}
}
这个方法内部实现很简单
这样就进入了InternalHandler的handleMessage(Message)里面了,而我们知道InternalHandler的Looper是Looper.getMainLooper(),所以处理Message是在主线程中,我们来看下代码
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;
}
}
}
通过代码,我们看到如果what为MESSAGE_POST_PROGRESS,则会在主线程中调用onProgressUpdate(result.mData),这也就是为什么我们平时在异步线程调用publishProgress(Progress...)方法后,可以在主线程中的onProgressUpdate(rogress... values)接受数据了。
其实在上面讲解过程中,我基本上已经把整体流程讲解过了,我这里补上一张图,比较全面的阐述了AsyncTask的执行流程如下:
asynctask执行流程.png
对应的时序图如下:
时序图.png
大家如果手机上看不清,我建议down下来在电脑上看。
如果结合AsyncTask的状态值,流程图如下:
流程.png
如果把AsyncTask和Handler分开则流程图如下:
AsyncTask和Handler分开.png
最后如果把AsyncTask里面所有类的涉及关系整理如下图:
20140513095959437.jpeg
总之,AsyncTask不失为一个非常好用的异步任务处理类。不过我从事Android开发5年多了,很少会用到AsyncTask,一般异步任务都是Handler。