AsyncTask源码分析

API版本 26
参考资料:Android开发艺术探索
概述
AsyncTask是底层用线程池和Handler来封装的抽象类。用来执行网络请求等耗时操作。可以创建此类的子类,并重写父类的方法。
AsyncTask的泛型参数

AsyncTask<Params, Progress, Result>

Params
其中第一个Params将做事doInBackground方法的参数类型。

Result doInBackground(Params... params);

此参数是通过AsyncTask中的execute(Params… params)传递到doInBackground(Params… params)方法中的。可以看出此参数可以传递多个。
Progress
Proress是publishProgress方法的参数类型。用于更新任务的执行进度。

onProgressUpdate(Progress... values)

Result
Result是postResult方法的参数类型。此方法的参数是doInBackground方法执行的返回结果。

postResult(Result result)

主要的回调方法
onPreExecute
此方法最先执行,在此方法中可以做一些数据的初始化。
doInBackground
此方法运行在主线程中,可以在此方法中做耗时操作。

  @Override
        protected String doInBackground(String... strings) {
            return null;
        }

onProgressUpdate
此方法运行在主线程中,在任务执行过程中,可以在doInBackground()方法中通过调用publishProgress();来回调此方法做一下进度的更新操作。
onPostExecute
此方法运行在主线程,当doInBackground方法执行结束后,将会回调此方法。可以在此方法中处理任务完成的逻辑。
AsyncTask的简单实用
布局
布局很简单,只是一个按钮,一个进度条。

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    tools:context="com.example.yeliang.testapplication.MainActivity">

    <Button
        android:id="@+id/btn_start"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="开始下载" />

    <ProgressBar
        android:id="@+id/pBar_progress"
        style="@android:style/Widget.ProgressBar.Horizontal"
        android:layout_width="match_parent"
        android:layout_height="2dp"
        android:max="100" />

</LinearLayout>

AsyncTask

private class DownLoadAsyncTask extends AsyncTask<String, Integer, String> {

        @Override
        protected void onPreExecute() {
            super.onPreExecute();
            progressBar.setProgress(0);
        }

        //运行在子线程中
        @Override
        protected String doInBackground(String... strings) {
            int progrss = 0;

            //模拟每次更新百分之20 更新五次
            for (int i = 0; i < 5; i++) {
                try {
                    //模拟耗时
                    Thread.currentThread().sleep(1000);
                    progrss += 20;
                } catch (InterruptedException e) {
                }

                //此方法会调用 onProgressUpdate
                publishProgress(progrss);
            }

            return strings[0];
        }


        @Override
        protected void onProgressUpdate(Integer... values) {
            super.onProgressUpdate(values);
            progressBar.setProgress(values[0]);
        }

        @Override
        protected void onPostExecute(String s) {
            super.onPostExecute(s);
            Toast.makeText(MainActivity.this, s + "已下载完成", Toast.LENGTH_LONG).show();
        }
    }

Activity
点击按钮使进度条模拟下载。

public class MainActivity extends AppCompatActivity {

    //进度条
    ProgressBar progressBar;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        Button btn = findViewById(R.id.btn_start);
        btn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                testAsyncTask();
            }
        });

        progressBar = findViewById(R.id.pBar_progress);
    }

    private void testAsyncTask() {
        new DownLoadAsyncTask().execute("downloadUrl---1", "downloadUrl---2");
    }
}

效果
这里写图片描述
源码分析
流程总览
这里写图片描述

类图总览
这里写图片描述

当创建一个AsyncTask对象时,最终都会调用下面这个构造方法
AsyncTask(@Nullable Looper callbackLooper)

在此方法中,首先会创建一个WorkerRunnable对象mWorker。并用mWorker来创建建FutureTask对象mFuture。
mWorker是一个Callable对象,所以当mFuture作为一个任务执行时,最终执行的是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);
                }
            }
        };
    }

execute方法是任务开始执行的触发点。在此方法中,调用了executeOnExecutor方法。
execute(Params… params)

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

executeOnExecutor(Executor exec,Params… params)
在此方法中主要做了三件事,如在注释中的说明:

@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)");
            }
        }

        //1 把当前的任务状态置为正在运行
        mStatus = Status.RUNNING;

        //2 回调onPreExecute方法给用户
        onPreExecute();

        mWorker.mParams = params;

        //3 执行在构造方法中创建的任务
        exec.execute(mFuture);

        return this;
    }

可以看到最终把任务的执行转交给了通过SerialExecutor。SerialExecutor的源码如下
SerialExecutor
SerialExecutor中维护了一个任务队列mTasks,当调用execute方法执行任务时,首先创建了一个任务并添加到mTasks中。然后调用scheduleNext()方法。在scheduleNext中直接通过线程池对象执行任务。
需要注意的是,SerialExecutor中的execute方法只是把将要执行的任务添加到任务队列中,而真正的执行是在scheduleNext方法中,通过线程池的对象去执行。
通过前面的AsyncTask中的executeOnExecutor方法的这一句

  exec.execute(mFuture);

可知,此处的execute方法的参数即为mFuture。而在前面说过mFuture是以mWorker来创建的。所以当线程池开始执行时,执行的是mWorker中的call方法。

 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();
            }
        }

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

WorkerRunnable
下面来看WorkerRunnable中的call方法。由于call方法是在线程池中执行的。所以此方法运行在子线程。在call方法中调用了doInBackground方法。所以doInBackground同样也是运行在子线程。
最后当doInBackground()方法执行完成后,调用postResult()方法。

 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;
            }

postResult(Result result)
在postResult方法中,只是通过Handler发送了一个消息。并把doInBackground方法中执行的结果对象作为Message的参数传递到Handler中

private Result postResult(Result result) {
        @SuppressWarnings("unchecked")
        Message message = getHandler().obtainMessage(MESSAGE_POST_RESULT,
                new AsyncTaskResult<Result>(this, result));
        message.sendToTarget();
        return result;
    }

InternalHandler
InternalHandler在此处的作用是把子线程执行的结果切换到主线程中。可以看到当消息类型为MESSAGE_POST_RESULT时,调用了
AsyncTask的finish()方法。

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;
            }
        }
    }

finish(Result result)
在finish()方法中,首先会调用onPostExecute()方法。然后把当前你的任务状态置为完成。至此任务的执行过程结束。

 private void finish(Result result) {
        if (isCancelled()) {
            onCancelled(result);
        } else {
            onPostExecute(result);
        }
        mStatus = Status.FINISHED;
    }

当任务正在执行时,可以调用publishProgress方法来更新任务的进度。
而因为任务执行在子线程,所以将会通过InternalHandler切换到主线程。

publishProgress(Progress… values)

@WorkerThread
    protected final void publishProgress(Progress... values) {
        if (!isCancelled()) {
            getHandler().obtainMessage(MESSAGE_POST_PROGRESS,
                    new AsyncTaskResult<Progress>(this, values)).sendToTarget();
        }
    }

根据上面这一段可知,此方法只是通过InternalHandler发送了一个消息。
而在的handleMessage()方法中:

 case MESSAGE_POST_PROGRESS:
                    result.mTask.onProgressUpdate(result.mData);
                    break;

把更新操作直接转交给了onProgressUpdate()方法。至此,AsyncTask中的介个回调方法都涉及到了。

猜你喜欢

转载自blog.csdn.net/SImple_a/article/details/80035763