Android知识

AsyncTask(基于Api25) 源码分析

2017-06-29  本文已影响0人  大文子_
介绍:

AsyncTask是一种轻量级的异步任务类,它可以在线程池中执行后台任务,然后把执行的进度和最终结果传递给主线程并在主线程中更新UI。
AsyncTask是一个抽象的泛型类,它提供了Params,Progress和Result这三个泛型参数,其中Params表示参数的类型,Progress表示后台任务的执行进度的类型,而Result则表示后台任务的返回结果的类型,如果AsyncTask确实不需要传递具体的参数,那么这三个泛型参数可以用Void来代替。AsyncTask这个类的生命如下:
public abstract class AsyncTask<Params, Progress, Result>

核心方法
  1. protected void onPreExecute()
    在AsyncTask被调用的线程中执行,在异步任务执行之前被调用
  2. protected abstract Result doInBackground(Params... params)
    在线程池中执行,执行异步任务,并返回其结果,params参数表示异步任务的输入参数。在此方法中可以通过publishProgress方法来更新任务的进度,publishProgress会发送消息间接调用onProgressUpdate方法
  3. protected void onProgressUpdate(Progress... values)
    在主线程中执行,当后台任务的执行进度发生改变时调用此方法
  4. protected void onPostExecute(Result result)
    在主线程中执行,在异步任务执行完成之后,此方法被调用,其result参数是后台任务的返回值

源码分析

为了分析AsyncTask的源码,我们从execute方法入手

//一个串行执行任务的线程池
private static volatile Executor sDefaultExecutor = SERIAL_EXECUTOR;

public final AsyncTask<Params, Progress, Result> execute(Params... params) {
        return executeOnExecutor(sDefaultExecutor, params);
}

public final AsyncTask<Params, Progress, Result> executeOnExecutor(Executor exec,
            Params... params) {
        //从这里可以看出AsyncTask只能被执行一次
        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)");
            }
        }
        //将AsyncTask置为RUNNING状态
        mStatus = Status.RUNNING;
        //此处调用onPreExecute方法
        onPreExecute();

        mWorker.mParams = params;
        exec.execute(mFuture);

        return this;
    }```
从代码中看出,execute会调用executeOnExecutor方法,其中有这么两行代码:

mWorker.mParams = params;
exec.execute(mFuture);```
那这个mWorker 和mFuture是哪里来的呢?
接着往下看:

public AsyncTask() {
        mWorker = new WorkerRunnable<Params, Result>() {
            public Result call() throws Exception {
                //将AsyncTask设置为已调用
                mTaskInvoked.set(true);
                Result result = null;
                try {
                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
                    //调用doInBackground方法
                    //noinspection unchecked
                    result = doInBackground(mParams);
                    Binder.flushPendingCommands();
                } catch (Throwable tr) {
                    mCancelled.set(true);
                    throw tr;
                } finally {
                    //最终调用postResult方法
                    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);
                }
            }
        };
    }```
原来,在AsyncTask的构造函数中,我们初就始化了mWorker 和mFuture变量,下面我们来看下这两个变量,通过看源码我们知道:
WorkerRunnable是一个封装了Params参数的Callable抽象类
FutureTask是一个实现了Runnable和Future<V>的类
从上面,我们知道executeOnExecutor 会调用exec.execute(mFuture),其最终会执行mFuture的run方法
下面让我们来看看FutureTask的run方法

public void run() {
if (state != NEW ||
!U.compareAndSwapObject(this, RUNNER, null, Thread.currentThread()))
return;
try {
Callable<V> c = callable;
if (c != null && state == NEW) {
V result;
boolean ran;
try {
//在这里调用了从FutureTask构造函数里传进来的mWorker的call方法
result = c.call();
ran = true;
} catch (Throwable ex) {
result = null;
ran = false;
setException(ex);
}
if (ran)
//最终会调用自身的done方法
set(result);
}
} finally {
// runner must be non-null until state is settled to
// prevent concurrent calls to run()
runner = null;
// state must be re-read after nulling runner to prevent
// leaked interrupts
int s = state;
if (s >= INTERRUPTING)
handlePossibleCancellationInterrupt(s);
}
}

protected void set(V v) {
if (U.compareAndSwapInt(this, STATE, NEW, COMPLETING)) {
outcome = v;
U.putOrderedInt(this, STATE, NORMAL); // final state
finishCompletion();
}
}
private void finishCompletion() {
// assert state > COMPLETING;
for (WaitNode q; (q = waiters) != null;) {
if (U.compareAndSwapObject(this, WAITERS, q, null)) {
for (;;) {
Thread t = q.thread;
if (t != null) {
q.thread = null;
LockSupport.unpark(t);
}
WaitNode next = q.next;
if (next == null)
break;
q.next = null; // unlink to help gc
q = next;
}
break;
}
}
//最终调用mFuture的done方法
done();

    callable = null;        // to reduce footprint

}

从以上代码我们可以分析出,mFuture的run方法会调用mWorker的call方法,并最终调用自己的done方法。
那我们接着看mWorker.call:

private static Handler getHandler() {
synchronized (AsyncTask.class) {
if (sHandler == null) {
sHandler = new InternalHandler();
}
return sHandler;
}
}

private Result postResult(Result result) {
@SuppressWarnings("unchecked")
Message message = getHandler().obtainMessage(MESSAGE_POST_RESULT,
new AsyncTaskResult<Result>(this, result));
message.sendToTarget();
return result;
}```
在mWorker.call中,我们调用了doInBackground方法,最终调用postResult
在上面的代码中,postResult方法会通过sHandler发送一个MESSAGE_POST_RESULT的消息,这个sHandler定义如下:

private static class InternalHandler extends Handler {
        public InternalHandler() {
            //切换到主线程
            super(Looper.getMainLooper());
        }

        @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;
            }
        }
}```
可以发现,sHandler收到MESSAGE_POST_RESULT消息后会调用AsyncTask的finish方法,如下所示:

private void finish(Result result) {
if (isCancelled()) {
onCancelled(result);
} else {
onPostExecute(result);
}
mStatus = Status.FINISHED;
}```
AsyncTask的finish方法逻辑比较简单,若果AsyncTask被取消了,那么久调用onCancelled方法,否则就会调用onPostExecute方法。
总结下来,AsyncTask的大致执行流程为:
AsyncTask.execute--->AsyncTask.executeOnExecutor
--->AsyncTask.onPreExecute--->mFuture.run--->mWorker.call
--->AsyncTask.doInBackground--->AsyncTask.postResult--->AsyncTask.finish
--->AsyncTask.onPostExecute or AsyncTask.onCancelled
--->mFuture.done
到这里AsyncTask的源码就分析完成了。

上一篇下一篇

猜你喜欢

热点阅读