AsyncTask注意事项

1、AsyncTask并不适合执行耗时的任务,对于耗时的任务建议使用线程池。

一个是因为对于串行版本的AsyncTask执行耗时任务会导致其他任务等待较长的时间才能执行,另一个是因为对于并行版本的AsyncTask执行耗时任务,可能会导致线程池中的线程一直被占用,被占用的线程多了,当有新的任务被添加的时候,会导致崩溃。具体原因,建议稍后阅读:AsyncTask源码分析-AsyncTask的串行执行和并行执行-AsyncTask缺陷

2、在某些安卓版本中AsyncTask必须在主线程中加载
具体请参考:为什么必须在主线程中加载 AsyncTask?

3、execute方法必须在主线程中被调用

因为execute中调用了executeOnExecutor方法,executeOnExecutor方法方法中调用了onPreExecute方法,而onPreExexute方法可能会做一些初始化UI的操作,所以execute方法必须在主线程中被调用。

4、不要在程序中直接的调用onPreExecute,doInBackground,onProgressUpdate,onPostExecute,onCancelled等方法

5、一个AsyncTask对象只能执行一次execute方法

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
@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;
}

这点从executeOnExecutor的源码中就可以看出。

6、注意串行和并行的问题

建议阅读:AsyncTask的串行执行和并行执行

当前网速较慢或者你使用的浏览器不支持博客特定功能,请尝试刷新或换用Chrome、Firefox等现代浏览器