一、使用案例
private class DownloadFilesTask extends AsyncTask {
@Override
// 任务执行前执行该方法
protected void onPreExecute() {
}
// 异步执行耗时操作
protected Long doInBackground(URL... urls) {
int count = urls.length;
long totalSize = 0;
for (int i = 0; i < count; i++) {
totalSize += Downloader.downloadFile(urls[i]);
// 将进度传递到方法onProgresUpdate()方法中
publishProgress((int) ((i / (float) count) * 100));
// Escape early if cancel() is called
if (isCancelled()) break;
}
return totalSize;
}
// ui 线程设置进度显示
protected void onProgressUpdate(Integer... progress) {
setProgressPercent(progress[0]);
}
// 任务执行完毕
protected void onPostExecute(Long result) {
showDialog("Downloaded " + result + " bytes");
}
// 任务取消时执行该方法
protected void onCancelled() {
}
}
二、方法调用顺序梳理
三、源码分析
谈到源码分析我们最好沿着一条脉络,一直跟进方法调用,接下来就从execute()方法作为入口,逐级跟进
execute()
@MainThread
public final AsyncTask<Params, Progress, Result> execute(Params... params) {
return executeOnExecutor(sDefaultExecutor, params);
}
调用了executeOnExecutor(sDefaultExecutor, params)方法,我们继续跟进
executeOnExecutor()
@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(),首先调用该方法
onPreExecute();
// 将所传参数类型设置给workRunnable参数类型中
mWorker.mParams = params;
// 执行execute()方法
exec.execute(mFuture);
return this;
}
本方法中首先调用了onPreExecute()方法,紧接着设置mWorker参数,最后调用了exec.execute()执行
此时几个参数需要明确一下:
mWorker: mWorker = new WorkerRunnable<Params, Result>() workerRunnable对象实例
exec:
private static volatile Executor sDefaultExecutor = SERIAL_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();
exec是一个SerialExecutor()对象实例
mFuture:是一个 FutureTask<Result>(mWorker)实例,将mWorker传进来
接下来我们继续跟进WorkerRunnable和SerialExecutor和FutureTask
WorkerRunnable
查看workRunnable 执行 mWorker.mParams = params;
/**
* 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
// 调用doInBackground,执行耗时操作
result = doInBackground(mParams);
Binder.flushPendingCommands();
} catch (Throwable tr) {
mCancelled.set(true);
throw tr;
} finally {
// 将结果post出去
postResult(result);
}
return result;
}
};
// 省略部分代码
}
查看WorkerRunnable实现Callable接口
private static abstract class WorkerRunnable<Params, Result> implements Callable<Result> {
Params[] mParams;
}
跟进查看Callable接口
The {@code Callable} interface is similar to {@link
* java.lang.Runnable}, in that both are designed for classes whose
* instances are potentially executed by another thread.
* Callable接口和runnable类似,实现另一个线程潜在执行而设计
@FunctionalInterface
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;
通过该方法我们知道doInBackground()方法在子线程中执行
沿着该方法继续跟进 postResult(result);
postResult()
查看postResult,通过handler消息将result发送出去
private Result postResult(Result result) {
@SuppressWarnings("unchecked")
Message message = getHandler().obtainMessage(MESSAGE_POST_RESULT,
new AsyncTaskResult<Result>(this, result));
message.sendToTarget();
return result;
}
此时引进了handler既然postResult()发送了一个消息what值是MESSAGE_POST_RESULT,我们继续查看下消息接收处做了什么
InternalHandler
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:
// There is only one result
// 执行该方法 继续跟踪
result.mTask.finish(result.mData[0]);
break;
case MESSAGE_POST_PROGRESS:
// 更新进度消息
result.mTask.onProgressUpdate(result.mData);
break;
}
}
}
继续跟进接收到消息后的操作
MESSAGE_POST_RESULT:执行result.mTask.finish(result.mData[0])
MESSAGE_POST_PROGRESS:执行result.mTask.onProgressUpdate
result.mTask.finish(result.mData[0])
result.mTask.finish(result.mData[0]);
如果任务被取消了回调onCancelled否则调用 onPostExecute(result);
private void finish(Result result) {
if (isCancelled()) {
onCancelled(result);
} else {
onPostExecute(result);
}
mStatus = Status.FINISHED;
}
此时MESSAGE_POST_PROGRESS:从哪里发送的呢,我们继续跟进,发现是在publishProgress(Progress… values)中调用
publishProgress(Progress… values)
在doInBackground()方法中可以根据需求调用执行该方法,将进度传递至onProgressUpdate()方法中
@WorkerThread
protected final void publishProgress(Progress... values) {
if (!isCancelled()) {
getHandler().obtainMessage(MESSAGE_POST_PROGRESS,
new AsyncTaskResult<Progress>(this, values)).sendToTarget();
}
}
result.mTask.onProgressUpdate(result.mData)
直接调用了onProgressUpdate()方法
result.mTask.onProgressUpdate(result.mData)
好的,workRubnnable中执行的操作我们已经跟进结束,还记得SerialExecutor没有跟进吗,下面继续跟进该方法执行
SerialExecutor
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() {
public void run() {
try {
r.run();
} finally {
// 重点查看该方法
scheduleNext();
}
}
});
if (mActive == null) {
scheduleNext();
}
}
调用了scheduleNext()
protected synchronized void scheduleNext() {
if ((mActive = mTasks.poll()) != null) {
// 调用线程池方法
THREAD_POOL_EXECUTOR.execute(mActive);
}
}
}
熟悉线程池基本使用的朋友应该对该方法很熟悉,此处就不介绍线程池的基本使用了
ThreadPoolExecutor
关于 THREAD_POOL_EXECUTOR,其实就是线程池的使用
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);
threadPoolExecutor.allowCoreThreadTimeOut(true);
THREAD_POOL_EXECUTOR = threadPoolExecutor;
}
里面涉及的几个参数也贴出来如下:
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);
FutureTask
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);
}
}
};
private void postResultIfNotInvoked(Result result) {
// 获取布尔值标记
final boolean wasTaskInvoked = mTaskInvoked.get();
if (!wasTaskInvoked) {
//如果任务没有调用,执行postResult()方法
postResult(result);
}
}
ok,源码整体的流程我们就分析完了。