一、使用方法
AsyncTask通常用于实现在后台线程中完成耗时操作,然后在主线程中更新UI。
继承AsyncTask需要指定3个泛型参数:
AsyncTask<Params, Progress, Result>
- Params: 启动任务执行的输入参数的类型
- Progress: 后台任务完成的进度值得类型
- Result: 后台执行任务完成后返回结果的类型
使用AsyncTask的主要方法:
- protected String doInBackground(Params... params)
在后台线程池中执行,可以调用publishProgress(Progress... values)方法触发onProgressUpdate方法,从而更新任务任务进度 - protected void onProgressUpdate(Progress... values)
在UI线程执行,更新进度条等UI - protected void onPreExecute()
在doInBackground方法之前UI线程执行,通常用于完成初始化工作。 - protected void onPostExecute(Result result)
在UI线程执行,在doInBackground方法之后会自动调用,并将doInBackground的返回值传给该方法。
使用AsyncTask必须遵守以下原则:
- 必须在UI线程创建AsyncTask实例,API26之后不需要
- 必须在UI线程中调用AsyncTask的execute()方法,因为onPreExecute需要在主线程回调
- 每个AsyncTask在后台任务执行完成前只能被执行一次,多次调用会引发异常
demo
public class MainActivity extends AppCompatActivity {
private TextView show = null;
private Button button = null;
private final String TAG = "MainActivity";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
show = (TextView)findViewById(R.id.show);
button = (Button)findViewById(R.id.button);
button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
try {
download();
} catch (MalformedURLException e) {
e.printStackTrace();
}
}
});
}
public void download() throws MalformedURLException {
MyAsyncTask task = new MyAsyncTask(this);
//AsyncTask第一个参数为Void,如果不是Void,execute方法需要传入参数。
task.execute();
}
class MyAsyncTask extends AsyncTask<Void, Integer, String> {
ProgressDialog pDialog;
int hasRead = 0;
Context mContext;
public MyAsyncTask(Context context) {
mContext = context;
}
@Override
protected String doInBackground(Void... params) {
StringBuilder sb = new StringBuilder();
try{
while (hasRead < 100) {
hasRead++;
sb.append(hasRead + " ");
publishProgress(hasRead);
Thread.sleep(200);
}
return sb.toString();
}catch (Exception e){
e.printStackTrace();
}
return null;
}
@Override
protected void onPreExecute() {
pDialog = new ProgressDialog(mContext);
pDialog.setTitle("任务正在执行中");
pDialog.setMessage("任务正在执行中, 敬请等待...");
pDialog.setCancelable(false);
pDialog.setMax(100);
pDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
pDialog.setIndeterminate(false);
pDialog.show();
}
@Override
protected void onProgressUpdate(Integer... values) {
show.setText("已经读取了【" + values[0] + "】行!");
pDialog.setProgress(values[0]);
}
@Override
protected void onPostExecute(String s) {
show.setText(s);
if (hasRead == 100) {
pDialog.dismiss();
}
}
}
}
[图片上传失败...(image-c5125d-1551414183649)]二、AsyncTask源码分析
首先来看下构造函数
/frameworks/base/core/java/android/os/AsyncTask.java
* Creates a new asynchronous task. This constructor must be invoked on the UI thread.
*/
public AsyncTask() {
this((Looper) null);
}
/**
* Creates a new asynchronous task. This constructor must be invoked on the UI thread.
*
* @hide
*/
public AsyncTask(@Nullable Handler handler) {
this(handler != null ? handler.getLooper() : null);
}
/**
* Creates a new asynchronous task. This constructor must be invoked on the UI thread.
*
* @hide
*/
public AsyncTask(@Nullable Looper callbackLooper) {
mHandler = callbackLooper == null || callbackLooper == Looper.getMainLooper()
? getMainHandler()
: new Handler(callbackLooper);
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;
}
};
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);
}
}
};
}
构造函数中首先创建了一个WorkerRunnable对象,我们看下WorkerRunnable定义:
private static abstract class WorkerRunnable<Params, Result> implements Callable<Result> {
Params[] mParams;
}
WorkerRunnable继承自Callable接口,Callable接口跟Runnable接口类似,只是其中的call方法带返回值
public interface Runnable {
public abstract void run();
}
public interface Callable<V> {
/**
* Computes a result, or throws an exception if unable to do so.
*
* @return computed result
* @throws Exception if unable to compute a result
*/
V call() throws Exception;
}
回到AsyncTask构造函数中,在WorkerRunnable的call方法中调用了doInBackground,doInBackground执行完后把结果传给postResult方法。继续往下看创建了FutureTask对象,FutureTask可以通过调用ExecutorService.submit执行参数Callable中的任务,也可以用于获得Callable任务的执行结果、查询是否完成和取消任务等操作。所以AsyncTask构造函数中主要工作是:
- 在一个Callable对象mWorker的call方法中,调用doInBackground方法,并将结果传给postResult方法
- 创建以mWorker作为参数的FutureTask对象mFuture。
接下来再看AsyncTask.execute()方法:
@MainThread
public final AsyncTask<Params, Progress, Result> execute(Params... params) {
return executeOnExecutor(sDefaultExecutor, params);
}
/**
* 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:
//如果任务没有结束mStatus状态为RUNNING,则会抛出异常,所以每个AsyncTask在后台任务执行完成前只能被执行一次,多次调用会引发异常
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;
}
execute() 方法直接调用executeOnExecutor传入默认的sDefaultExecutor,是串行Executor,executeOnExecutor()方法首先回调onPreExecute(),然后调用sDefaultExecutor.execute()执行构造函数中的Callable任务mWorker,下面看下sDefaultExecutor的定义:
/**
* 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 volatile Executor sDefaultExecutor = SERIAL_EXECUTOR;
private static class SerialExecutor implements Executor {
//Runnable缓存队列
final ArrayDeque<Runnable> mTasks = new ArrayDeque<Runnable>();
//mActive正在执行的Runnable
Runnable mActive;
public synchronized void execute(final Runnable r) {
mTasks.offer(new Runnable() {
public void run() {
try {
//mFuture的run()方法会调用mWorker的call()方法
r.run();
} finally {
//执行完一个任务后再从缓存队列中取下一个
scheduleNext();
}
}
});
//第一次mActive为null,直接调用scheduleNext
if (mActive == null) {
scheduleNext();
}
}
protected synchronized void scheduleNext() {
if ((mActive = mTasks.poll()) != null) {
//真正在线程池中开始执行任务
THREAD_POOL_EXECUTOR.execute(mActive);
}
}
}
SerialExecutor主要作用请参考注释,其实SerialExecutor的作用是保证来的线程是串行执行的,真正在后台开始执行任务是THREAD_POOL_EXECUTOR.execute(mActive)
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());
}
};
//缓存队列,用来存储执行的任务,基于链表的先进先出队列,这里指定长度为128
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;
static {
ThreadPoolExecutor threadPoolExecutor = new ThreadPoolExecutor(
CORE_POOL_SIZE, MAXIMUM_POOL_SIZE, KEEP_ALIVE_SECONDS, TimeUnit.SECONDS,
sPoolWorkQueue, sThreadFactory);
//但是如果调用了allowCoreThreadTimeOut(boolean)方法,在线程池中的线程数不大于corePoolSize时,keepAliveTime参数也会起作用,直到线程池中的线程数为0;
threadPoolExecutor.allowCoreThreadTimeOut(true);
THREAD_POOL_EXECUTOR = threadPoolExecutor;
}
java.uitl.concurrent.ThreadPoolExecutor类是线程池中最核心的一个类,这里创建ThreadPoolExecutor对象的几个重要参数:
- CORE_POOL_SIZE
线程池中的核心线程个数,当线程池中线程数小于CORE_POOL_SIZE时,进来新任务就创建线程,当大于CORE_POOL_SIZE时,则放入缓存队列中,这里定义为2到4个。 - MAXIMUM_POOL_SIZE
线程池中最大线程个数,当缓存队列已满或者任务剧增时,最多可以创建的线程个数,这里为 CPU_COUNT * 2 + 1 - KEEP_ALIVE_SECONDS
表示线程没有任务执行时最多保持多久时间会终止。默认情况下,只有当线程池中的线程数大于corePoolSize时,keepAliveTime才会起作用,直到线程池中的线程数不大于corePoolSize,这里是30s - TimeUnit.SECONDS
keepAliveTime的时间单位为s - sPoolWorkQueue
线程池缓存队列 - sThreadFactory
线程工厂,用来创建线程
回到前面构造函数中执行完后台任务doInBackground,会调用postResult处理结果
private Result postResult(Result result) {
@SuppressWarnings("unchecked")
Message message = getHandler().obtainMessage(MESSAGE_POST_RESULT,
new AsyncTaskResult<Result>(this, result));
message.sendToTarget();
return result;
}
这里getHandler()通常返回InternalHandler的静态实例sHandler
private static InternalHandler sHandler;
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:
//这里回调onPostExecut
result.mTask.finish(result.mData[0]);
break;
case MESSAGE_POST_PROGRESS:
result.mTask.onProgressUpdate(result.mData);
break;
}
}
}
sHandler绑定的主线程的Looper,这就保证了onProgressUpdate和onPostExecute函数在主线程中回调
private static Handler getMainHandler() {
synchronized (AsyncTask.class) {
if (sHandler == null) {
sHandler = new InternalHandler(Looper.getMainLooper());
}
return sHandler;
}
}
-
关于串行并行问题
串行:
直接调用execute方法使用默认的Executor: SERIAL_EXECUTOR,这是个静态实例,所以适用于以下有多个任务的情况下,保证串行执行
MyAsyncTask task1 = new MyAsyncTask(); MyAsyncTask task2 = new MyAsyncTask(); MyAsyncTask task3 = new MyAsyncTask(); ... ... task1.execute(); task2.execute(); task3.execute();
并行:
如果希望并行执行任务则需要调用方法executeOnExecutor(),传入参数Executor:THREAD_POOL_EXECUTOR
MyAsyncTask task1 = new MyAsyncTask(); MyAsyncTask task2 = new MyAsyncTask(); MyAsyncTask task3 = new MyAsyncTask(); ... ... task1.executeOnExecutor(THREAD_POOL_EXECUTOR,...); task2.executeOnExecutor(THREAD_POOL_EXECUTOR,...); task3.executeOnExecutor(THREAD_POOL_EXECUTOR,...);