AsyncTask 抽象泛型类
内部实现原理是2个线程池和Handler
泛型<Params,Progress,Result>
Params 为参数类型 progress 为后台任务执行进度的类型 Result返回结果的类型
四个方法
onPreExecute()在主线程中执行。在任务执行前做一些准备
doInBackground(Params... params) 在线程中执行。执行一些比较耗时的操作,可以使用publishProgress(Progress...values)来更新进度信息
onProgressUpdate(Progress... values) 在主线程中执行,此方法可以对控件进行更新
onPostExecute(Result result) 在主线程中执行。当后台任务执行完成后,返回的结果
AsyncTask.class
private final WorkerRunnable<Params,Result> mWorker;
private final FutureTask<Result>mFuture;
// 构造方法
AsyncTask(){// 定义了WorkerRunnable和FutureTask
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);//实现了doInBackground抽象方法
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);
}
}
};
// 执行方法
Executor(){// 初始化一个串行的线程池SerialExecutor来执行FutureTask
exec.execute(mFuture)
private static class SerialExecutor implements Executor {
final ArrayDeque<Runnable> mTasks = new ArrayDeque<Runnable>();// 任务队列(排序任务)
Runnable mActive;
public synchronized void execute(final Runnable r) {
mTasks.offer(new Runnable() {// 将FutureTask任务存到mTask任务队列中
public void run() {
try {
r.run();// FutureTask的run方法会执行到WorkerRunnable的call方法
} finally {
scheduleNext();// 任务添加到队列之后
}
}
});
if (mActive == null) {
scheduleNext();
}
}
protected synchronized void scheduleNext() {
if ((mActive = mTasks.poll()) != null) {
THREAD_POOL_EXECUTOR.execute(mActive);//取出队列中的任务,提交给Thread_POOL_EXECUTOR线程池来处理
}
}
}
THREAD_POOL_EXECUTOR 指的是threadPoolExecutor
Thread_POOL_EXECUTOR.execute(mActive)执行任务,会执行FutureTask的run方法,
然后调用到WorkerRunnable的call方法会将结果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() 在当前线程为UI线程时等价于 getMainHandler()
private static Handler getMainHandler() {
synchronized (AsyncTask.class) {
if (sHandler == null) {
sHandler = new InternalHandler(Looper.getMainLooper());
}
return 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:// 接收到MESSAGE_POST_RESULT消息后,会调用
// There is only one result
result.mTask.finish(result.mData[0]);//回调onPostExecute(result)
break;
case MESSAGE_POST_PROGRESS:
result.mTask.onProgressUpdate(result.mData);
break;
}
}
}