之前写的AsyncTask 写的不太清晰 今天重新写一下
首先说明一下它的五个常用方法:
onProExecute(): 主线程中执行
doInBackground(Params… params) 线程池中执行 执行异步任务
onProgressUpdate(Progress … value) 主线程更新进度
onPostExecute(Result result) 回调结果
onCancle() 取消
AsyncTask 工作原理
开始分析
@MainThread
public final AsyncTask<Params, Progress, Result> execute(Params... params) {
return executeOnExecutor(sDefaultExecutor, params);// first
}
first 调用代码如下
@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);// second
return this;
}
当状态为running 或者 finish 的时候都会抛出相应的异常
接着准备工作调用onPreExecute();—————–使用onPreExecute()准备工作
exec.execute(mFuture);
thread 调用代码如下
@MainThread
public static void execute(Runnable runnable) {
sDefaultExecutor.execute(runnable);
}
生命变量的时候
private static volatile Executor sDefaultExecutor = SERIAL_EXECUTOR;
public static final Executor SERIAL_EXECUTOR = new SerialExecutor();
所以 最终执行的execute 实在 类 SerialExecutor 中调用了execute 方法
代码如下
`
private static class SerialExecutor implements Executor {
final ArrayDeque mTasks = new ArrayDeque();
Runnable mActive;
public synchronized void execute(final Runnable r) {
mTasks.offer(new Runnable() {
public void run() {
try {
r.run(); // mFuture 调用 run 方法
} finally {
scheduleNext();
}
}
});
if (mActive == null) {
scheduleNext();
}
}
protected synchronized void scheduleNext() {
if ((mActive = mTasks.poll()) != null) {
THREAD_POOL_EXECUTOR.execute(mActive);
}
}
}
`
上出代码可见 上述 执行完 r.run 后最终回调用 scheduleNext 然后 如果 mActive 对象不存在的话
将传入的mFuture 对象从 队列中取出 赋值 给 mActivie 盘后 执行
THREAD_POOL_EXECUTOR.execute(mActive);
在上述代码块
public synchronized void execute(final Runnable r) {
mTasks.offer(new Runnable() {
public void run() {
try {
r.run(); // mFuture 调用 run 方法
} finally {
scheduleNext();
}
}
});
if (mActive == null) {
scheduleNext();
}
mFuture 调用 run 方法 会触发 mWorker 的 call 方法
代码如下
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);
}
}
};
}
其中 result = doInBackground(mParams);
由此可见 doInBackground 是在线程池中执行
同时 doInBackground 返回结果 在
postResult(result);返回
看一下 代码
Message message = getHandler().obtainMessage(MESSAGE_POST_RESULT,
new AsyncTaskResult<Result>(this, result));
message.sendToTarget();
return 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;
}
}
}
result.mTask.finish(result.mData[0]);
方法继续调用
private void finish(Result result) {
if (isCancelled()) {
onCancelled(result);
} else {
onPostExecute(result);
}
mStatus = Status.FINISHED;
}
多说一个为何 我们要在onPorgressUpdate()中输出progress 的时候 为何要在 doInBackground 中 调用
publishProgress
@WorkerThread
protected final void publishProgress(Progress... values) {
if (!isCancelled()) {
getHandler().obtainMessage(MESSAGE_POST_PROGRESS,
new AsyncTaskResult<Progress>(this, values)).sendToTarget();
}
}
源码中 当调用publishProgress 触发 发送what == MESSAGE_POST_PROGRESS 的消息
同样在
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;
}
代码快中接受并调用 onProgressUpdate方法达到更新进度条的目地