AsyncTask原理
前言
在Android开发中经常会通过线程去执行耗时的任务,并且在任务执行完之后通常会用到Handler来更新UI。虽然实现简单,但是有多个任务同时执行时则会显得代码很臃肿。Android提供了AsyncTask,它使得异步任务实现起来更加简单,代码更简洁。
AsyncTask介绍
AsyncTask是一个抽象的泛型类,它有3个泛型参数,分别为Params、Progress和Result。
Params:参数类型,
Progress:后台任务执行进度的类型,
Result:返回结果的类型。
如果不需要某个参数,可以将其设置为Void类型。
AsyncTask如下:
public abstract class AsyncTask<Params, Progress, Result> {
}
AsyncTask中有4个核心方法:
1、onPreExecute():在主线程中执行。一般在任务执行前做准备工作。
2、doInBackground(Params…params):在线程池中执行。在 onPreExecute方法执行后运行,用来执行耗时操作。在执行过程中可以调用publishProgress(Progress…values)方法来更新进度信息。
3、onProgressUpdate(Progress…values):在主线程中执行。当调用publishProgress(Progress…values)方法时,此方法会将进度更新到UI组件上。
4、onPostExecute(Result result):在主线程中执行。当后台任务执行完成后,会被执行。doInBackground方法得到的结果就是返回的result的值。
源码分析
接下来分析一下AsyncTask的源码。首先看下构造方法:
/**
* 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判空
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);//在call方法中调用了doInBackground(mParams)来处理任务并得到结果
Binder.