AsyncTask源码分析(基于android7.1)

AsyncTask源码分析:
AsyncTask是一种轻量级的异步任务类,它是一个泛型抽象类,提供了Params, Progress, Result这三个泛型参数:其中Params表示参数的类型,Progress表示后台任务的执行进度的类型,而Result则表示后台任务的返回结果的类型.
AsyncTask提供了四个核心方法:
1.onPreExecute(),在主线程中执行,在异步任务执行之前,此方法会被调用,一般可以用于做些准备工作。
2.doInBackground(Params... params),抽象方法,在线程池中执行,此方法用于执行异步任务。
3.onProgressUpdate(Progress... values),在主线程中执行,当后台任务的执行进度发生改变时此方法会被调用。
4.onPostExecute(Result result),在主线程中执行,在异步任务执行之后,此方法会被调用,其中result参数是后台任务的返回值,即doInBackground的返回值。
AsyncTask默认是串行执行任务,当然我们也可以通过AsyncTask的executeOnExecutor方法来并行地执行任务。
AsyncTask的工作原理:
我们从它的execute方法开始分析,
(1)execute方法会调用executeOnExecutor方法,实现代码如下:

public final AsyncTask execute(Params... params) {
        return executeOnExecutor(sDefaultExecutor, params);
}```
```java
public final AsyncTask 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);

        return this;
    }```
(2) 我们看到传了一个sDefaultExecutor参数,那sDefaultExecutor是什么呢,接着看,
 ```java
public static final Executor SERIAL_EXECUTOR = new SerialExecutor();
private static volatile Executor sDefaultExecutor = SERIAL_EXECUTOR;
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();
                    } finally {
                        scheduleNext();
                    }
                }
            });
            if (mActive == null) {
                scheduleNext();
            }
        }

        protected synchronized void scheduleNext() {
            if ((mActive = mTasks.poll()) != null) {
                THREAD_POOL_EXECUTOR.execute(mActive);
            }
        }
    }

    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;
    }```
SerialExecutor实际上就是一个Executor,它保证了Runnable的串行执行。
当执行SerialExecutor的execute(final Runnable r)方法时,会把一个Runnable加入到mTasks队列尾部,第一次执行时,mActive为null,紧接着就调用scheduleNext(),scheduleNext方法会从mTasks取出第一个Runnable,在THREAD_POOL_EXECUTOR中执行,此Runnable执行后会再次执行scheduleNext()方法,以此来实现Runnable的串行执行。
(3) 在executeOnExecutor中 ,判断当前AsyncTask的状态,如果还没被执行,则将其状态置为Status.RUNNING,紧接着调用onPreExecute()方法,否则当该AsyncTask正在运行或已完成则抛出异常。
接着往下看,我们看到了两个变量mWorker,mFuture。其实,mWorker是一个Callable,而mFuture则是一个RunnableFuture,它们都是在AsyncTask的构造函数中被初始化的。当执行exec.execute(mFuture)方法时,会调用mFuture.run(),在mFuture的run()方法中调用了mWorker.call()
(4)接下来我们看看doInBackground和onPostExecute是何时被调用的,代码如下
```java
mWorker = new WorkerRunnable() {
            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;
            }
        };```
mWorker在执行call()方法时,会将mTaskInvoked标记为true,表示这个task已经被调用,紧接着会调用doInBackground(mParams)方法,并最终调用postResult(result)方法。
(5) 那postResult方法又是做什么的呢,接着看代码
```java
private Result postResult(Result result) {
        @SuppressWarnings("unchecked")
        Message message = getHandler().obtainMessage(MESSAGE_POST_RESULT,
                new AsyncTaskResult(this, result));
        message.sendToTarget();
        return result;
    }```
postResult的主要作用是向Hanlder发送MESSAGE_POST_RESULT类型消息,那Handler是如何处理的呢,接着往下看
```java
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;
            }
        }
    }```
Handler收到MESSAGE_POST_RESULT类型的消息后,会调用自己的finish()方法,接着看代码
```java
private void finish(Result result) {
        if (isCancelled()) {
            onCancelled(result);
        } else {
            onPostExecute(result);
        }
        mStatus = Status.FINISHED;
    }

可以看到如果改AysncTask没有被取消的话,就会调用 onPostExecute(result)方法,否则调用 onCancelled(result),最后将AysncTask的状态置为Status.FINISHED。
(6) 当mWorker.call()执行完之后,会调用mFuture.done()方法

 mFuture = new FutureTask(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);
                }
            }
        };

postResultIfNotInvoked(get())会被执行

private void postResultIfNotInvoked(Result result) {
        final boolean wasTaskInvoked = mTaskInvoked.get();
        if (!wasTaskInvoked) {
            postResult(result);
        }
    }

postResultIfNotInvoked方法主要是判断,如果这个AysncTask还未被执行,则调用postResult()来最终执行onPostExecute(Result result)方法

你可能感兴趣的:(AsyncTask源码分析(基于android7.1))