• Android源代码解析之(三)-->异步任务AsyncTask


    转载请标明出处:一片枫叶的专栏

    上一篇文章中我们解说了android中的异步消息机制。

    主要解说了Handler对象的使用方式。消息的发送流程等。android的异步消息机制是android中多任务处理的基础,Handler是整个android应用层体系异步消息传递的基础组件,通过对Handler源代码的解析的解析相信大家对android中的异步消息机制有了一个大概的了解。很多其它关于android中的异步消息机制的知识可參考我的:android源代码解析之(二)–>异步消息机制

    android的异步任务体系中另一个很重要的操作类:AsyncTask。其内部主要使用的是java的线程池和Handler来实现异步任务以及与UI线程的交互。本文我们将从源代码角度分析一下AsyncTask的基本使用和实现原理。

    基本使用:

    首先我们来看一下AsyncTask的基本使用:

    /**
     * 自己定义AsyncTask对象
     */
    class MAsyncTask extends AsyncTask<Integer, Integer, Integer> {
            @Override
            protected void onPreExecute() {
                super.onPreExecute();
                Log.i(TAG, "onPreExecute...(開始运行后台任务之前)");
            }
    
            @Override
            protected void onPostExecute(Integer i) {
                super.onPostExecute(i);
                Log.i("TAG", "onPostExecute...(開始运行后台任务之后)");
            }
    
            @Override
            protected Integer doInBackground(Integer... params) {
                Log.i(TAG, "doInBackground...(開始运行后台任务)");
                return 0;
            }
        }

    我们定义了自己的MAsyncTask并继承自AsyncTask。并重写了当中的是哪个回调方法:onPreExecute(),onPostExecute(),doInBackground();
    然后開始调用异步任务:

    /**
     * 開始运行异步任务
     */
    new MAsyncTask().execute();

    怎么样?AsyncTask的使用还是比較简单的。通过简单的几段代码就是实现了异步消息的调用与运行。以下我们将从这里的使用方式開始分析一下其内部的实现原理。

    源代码解析:

    好了。以下我们開始分析异步任务的运行过程,因为我们是首先new出了一个AsyncTask对象,然后才运行了execute方法,所以我们首先查看一下异步任务的构造方法:

    /**
         * Creates a new asynchronous task. This constructor must be invoked on the UI thread.
         */
        public AsyncTask() {
            mWorker = new WorkerRunnable<Params, Result>() {
                public Result call() throws Exception {
                    mTaskInvoked.set(true);
    
                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
                    //noinspection unchecked
                    Result result = doInBackground(mParams);
                    Binder.flushPendingCommands();
                    return postResult(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和FutureTask对象,熟悉java的童鞋应该知道这两个类事实上是java里面线程池相关的概念。其详细使用方法大家能够在网上查询,这里详细的细节不在表述,我们这里的重点是对异步任务总体流程的把握。

    所以:异步任务的构造方法主要用于初始化线程池先关的成员变量。

    接下来我们在看一下AsyncTask的開始运行方法:execute

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

    这里发现该方法中加入一个@MainThread的注解,通过该注解。能够知道我们在运行AsyncTask的execute方法时。仅仅能在主线程中运行。这里能够实验一下:

    /**
     * 測试代码,測试在子线程中通过MAsyncTask运行异步操作
     */
    new Thread(new Runnable() {
                        @Override
                        public void run() {
                            Log.i("tag", Thread.currentThread().getId() + "");
                            new MAsyncTask().execute();
                        }
                    }).start();
                    Log.i("tag", "mainThread:" + Thread.currentThread().getId() + "");

    然后运行,可是并没有什么差别。程序还是能够正常运行,我的手机的Android系统是Android5.0,详细原因尚未找到。欢迎有知道答案的童鞋能够相互沟通哈。

    可是这里须要基本的一个问题是:onPreExecute方法是与開始运行的execute方法是在同一个线程中的,所以假设在子线程中运行execute方法,一定要确保onPreExecute方法不运行刷新UI的方法。否则:

    @Override
            protected void onPreExecute() {
                super.onPreExecute();
                title.setText("########");
                Log.i(TAG, "onPreExecute...(開始运行后台任务之前)");
            }

    运行这段代码之后就会抛出异常,详细的异常信息例如以下:

    Process: com.example.aaron.helloworld, PID: 659
                                                                               android.view.ViewRootImpl$CalledFromWrongThreadException: Only the original thread that created a view hierarchy can touch its views.
                                                                                   at android.view.ViewRootImpl.checkThread(ViewRootImpl.java:6981)
                                                                                   at android.view.ViewRootImpl.requestLayout(ViewRootImpl.java:1034)
                                                                                   at android.view.View.requestLayout(View.java:17704)
                                                                                   at android.view.View.requestLayout(View.java:17704)
                                                                                   at android.view.View.requestLayout(View.java:17704)
                                                                                   at android.view.View.requestLayout(View.java:17704)
                                                                                   at android.widget.RelativeLayout.requestLayout(RelativeLayout.java:380)
                                                                                   at android.view.View.requestLayout(View.java:17704)
                                                                                   at android.widget.TextView.checkForRelayout(TextView.java:7109)
                                                                                   at android.widget.TextView.setText(TextView.java:4082)
                                                                                   at android.widget.TextView.setText(TextView.java:3940)
                                                                                   at android.widget.TextView.setText(TextView.java:3915)
                                                                                   at com.example.aaron.helloworld.MainActivity$MAsyncTask.onPreExecute(MainActivity.java:53)
                                                                                   at android.os.AsyncTask.executeOnExecutor(AsyncTask.java:587)
                                                                                   at android.os.AsyncTask.execute(AsyncTask.java:535)
                                                                                   at com.example.aaron.helloworld.MainActivity$1$1.run(MainActivity.java:40)
                                                                                   at java.lang.Thread.run(Thread.java:818)

    若在子线程中运行execute方法,那么这时候假设在onPreExecute方法中刷新UI,会报错,即子线程中不能更新UI。

    PS:为什么在子线程中不能更新UI呢?这里临时记住这个问题,兴许的文章中我们将介绍这个问题。

    继续看刚才的execute方法,我们能够发现其内部调用了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();
    
            mWorker.mParams = params;
            exec.execute(mFuture);
    
            return this;
        }

    能够看到其详细的内部实现方法里:首先推断当前异步任务的状态,其内部保存异步任务状态的成员变量mStatus的默认值为Status.PENDING,所以第一次运行的时候并不抛出这两个异常,那么什么时候回进入这个if推断并抛出异常呢,通过查看源代码能够知道,当我们运行了execute方法之后。假设再次运行就会进入这里的if条件推断并抛出异常,这里能够尝试一下:

    final MAsyncTask mAsyncTask = new MAsyncTask();
            title.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    /*MLog.e("you have clicked the title textview!!!");
                    Intent intent = new Intent(MainActivity.this, SecondActivity.class);
                    startActivityForResult(intent, 101);*/
    
    
                    new Thread(new Runnable() {
                        @Override
                        public void run() {
                            Log.i("tag", Thread.currentThread().getId() + "");
                            mAsyncTask
                                    .execute();
                        }
                    }).start();
                    Log.i("tag", "mainThread:" + Thread.currentThread().getId() + "");
    
                }
            });

    这里我们能够看到我们定义了一个AsyncTask的对象,而且每次运行点击事件的回调方法都会运行execute方法,当我们点击第一次的时候程序正常运行。可是当我们运行第二次的时候。程序就崩溃了。

    若这时候第一次运行的异步任务尚未运行完毕则会抛出异常:

    Cannot execute task:the task is already running.

    若第一次运行的异步任务已经运行完毕,则会抛出异常:

    Cannot execute task:the task has already been executed (a task can be executed only once)

    继续往下看,在executeOnExecutor中若没有进入异常分之。则将当前异步任务的状态更改为Running。然后回调onPreExecute()方法。这里能够查看一下onPreExecute方法事实上是一个空方法,主要就是为了用于我们的回调实现,同一时候这里也说明了onPreExecute()方法是与execute方法的运行在同一线程中。

    然后将execute方法的參数赋值给mWorker对象那个,最后运行exec.execute(mFuture)方法,并返回自身。

    这里我们重点看一下exec.execute(mFuture)的详细实现。这里的exec事实上是AsyncTask定义的一个默认的Executor对象:

    private static volatile Executor sDefaultExecutor = SERIAL_EXECUTOR;

    那么。SERIAL_EXECUTOR又是什么东西呢?

    public static final Executor SERIAL_EXECUTOR = new SerialExecutor();

    继续查看SerialExecutor的详细实现:

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

    能够发现其继承Executor类其内部保存着一个Runnable列表,即任务列表,在刚刚的execute方法中运行的exec.execute(mFuture)方法就是运行的这里的execute方法。
    这里详细看一下execute方法的实现:

    • 首先调用的是mTasks的offer方法,即将异步任务保存至任务列表的队尾

    • 推断mActive对象是不是等于null。第一次运行是null,然后调用scheduleNext()方法

    • 在scheduleNext()这种方法中会从队列的头部取值,并赋值给mActive对象。然后调用THREAD_POOL_EXECUTOR去运行取出的取出的Runnable对象。

    • 在这之后假设再有新的任务被运行时就等待上一个任务运行完毕后才会得到运行,所以说同一时刻仅仅会有一个线程正在运行。

    • 这里的THREAD_POOL_EXECUTOR事实上是一个线程池对象。

    然后我们看一下运行过程中mWorker的运行逻辑:

    mWorker = new WorkerRunnable<Params, Result>() {
                public Result call() throws Exception {
                    mTaskInvoked.set(true);
    
                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
                    //noinspection unchecked
                    Result result = doInBackground(mParams);
                    Binder.flushPendingCommands();
                    return postResult(result);
                }
            };

    能够看到在运行线程池的任务时,我们回调了doInBackground方法,这也就是我们重写AsyncTask时重写doInBackground方法是后台线程的原因。

    然后在任务运行完毕之后会回调我们的done方法:

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

    这里我们详细看一下postResultIfNotInvoked方法:

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

    其内部还是调用了postResult方法:

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

    这里能够看到起调用了内部的Handler对象的sendToTarget方法。发送异步消息,详细handler相关的内容能够參考:
    android源代码解析之(二)–>异步消息机制

    追踪代码。能够查看AsyncTask内部定义了一个Handler对象:

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

    能够看到起内部的handleMessage方法,有两个处理逻辑,各自是:更新进入条和运行完毕,这里的更新进度的方法就是我们重写AsyncTask方法时重写的更新进度的方法,这里的异步任务完毕的消息会调用finish方法:

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

    这里AsyncTask首先会推断当前任务是否被取消,若被取消的话则直接运行取消的方法,否则运行onPostExecute方法。也就是我们重写AsyncTask时须要重写的异步任务完毕时回调的方法。

    事实上整个异步任务的大概流程就是这样子的,当中涉及的知识点比較多。这里总结一下:

    • 异步任务内部使用线程池运行后台任务,使用Handler传递消息;

    • onPreExecute方法主要用于在异步任务运行之前做一些操作,它所在线程与异步任务的execute方法所在的线程一致。这里若须要更新UI等操作,则execute方法不能再子线程中运行。

    • 通过刚刚的源代码分析能够知道异步任务通常是顺序运行的,即一个任务运行完毕之后才会运行下一个任务。

    • doInBackground这种方法所在的进程为任务所运行的进程,在这里能够进行一些后台操作。

    • 异步任务运行完毕之后会通过一系列的调用操作。终于回调我们的onPostExecute方法

    • 异步任务对象不能运行多次。即不能创建一个对象运行多次execute方法。

      (通过execute方法的源代码能够得知)

    • 全部源代码基于android23。中间有什么疏漏欢迎指正。

    另外对android源代码解析方法感兴趣的可參考我的:
    android源代码解析之(一)–>android项目构建过程
    android源代码解析之(二)–>异步消息机制


    本文以同步至github中:https://github.com/yipianfengye/androidSource,欢迎star和follow


  • 相关阅读:
    WKT转换工具terraformers
    关于微信公众号投票结果的通告
    个人博客03
    个人博客02
    个人博客01
    四则运算2
    学习进度条
    构建之法阅读笔记01
    错误随笔
    软件工程概论第一节
  • 原文地址:https://www.cnblogs.com/clnchanpin/p/7203888.html
Copyright © 2020-2023  润新知