Android:AsyncTask源码解读

qinli0606 7年前
   <h2><strong>标题党</strong></h2>    <p>AsyncTask源码解读,解读这么流弊的标题,吓得我都不敢写下去啦!菜鸟一枚,写不对的地方,请各位大神在留下评论或拍砖,我会为大家贡献更多多的妹子图。</p>    <p style="text-align:center"><img src="https://simg.open-open.com/show/d7866d9061648d94d0d7f068e28809a1.jpg"></p>    <p>PS妹子图镇楼,可以增加阅读量</p>    <h2><strong>AsyncTask简单使用</strong></h2>    <ol>     <li> <p>直接上代码,很简单就是在子线程中结算1到100的和。妹子你走开,我要开始撸代码啦!</p> <pre>  <code class="language-java">public static void main(String arg[]) throws InterruptedException {       MyTask task = new MyTask();       task.execute(100);   }  static class MyTask extends AsyncTask<Integer, Integer, Integer> {       @Override       protected void onPreExecute() {           System.out.println("onPreExecute");           super.onPreExecute();       }       @Override       protected void onProgressUpdate(Integer... values) {           System.out.println("onProgressUpdate " + values[0]);           super.onProgressUpdate(values);       }       @Override       protected Integer doInBackground(Integer... integers) {           //在新的线程中执行           int sum = 0;           for (int i = 0; i < integers[0]; i++) {               sum = sum + i;               publishProgress(i);//给InternalHandler发送进度更新的消息           }           return sum;       }         @Override       protected void onPostExecute(Integer integer) {           //将子线程的结果post到主线程           super.onPostExecute(integer);       }   }</code></pre> </li>     <li> <p>稍微介绍重要的几个方法;暂时忘记到妹子图吧!看看以下四个方法:@MainThread表示在主线程中执行,而@WorkerThread表示在子线程中执行</p> <pre>  <code class="language-java">@MainThread  protected void onPreExecute()   @MainThread  protected void onPostExecute(Result result)   @MainThread  protected void onProgressUpdate(Progress... values)  @WorkerThread  protected abstract Result doInBackground(Params... params)</code></pre>      <ul>       <li> <p>onPreExecute:表示该方法是运行在主线程中的。在AsyncTask执行了execute()方法后就会在UI线程上执行onPreExecute()方法,该方法在task真正执行前运行,我们通常可以在该方法中显示一个进度条,从而告知用户后台任务即将开始。</p> </li>       <li> <p>doInBackground :表示该方法是运行在单独的工作线程中的,而不是运行在主线程中。doInBackground会在onPreExecute()方法执行完成后立即执行,该方法用于在工作线程中执行耗时任务,我们可以在该方法中编写我们需要在后台线程中运行的逻辑代码,由于是运行在工作线程中,所以该方法不会阻塞UI线程。该方法接收Params泛型参数,参数params是Params类型的不定长数组,该方法的返回值是Result泛型,由于doInBackgroud是抽象方法,我们在使用AsyncTask时必须重写该方法。在doInBackground中执行的任务可能要分解为好多步骤,每完成一步我们就可以通过调用AsyncTask的publishProgress(Progress…)将阶段性的处理结果发布出去,阶段性处理结果是Progress泛型类型。当调用了publishProgress方法后,处理结果会被传递到UI线程中,并在UI线程中回调onProgressUpdate方法,下面会详细介绍。根据我们的具体需要,我们可以在doInBackground中不调用publishProgress方法,当然也可以在该方法中多次调用publishProgress方法。doInBackgroud方法的返回值表示后台线程完成任务之后的结果。</p> </li>       <li> <p>onProgressUpdate 上面我们知道,当我们在doInBackground中调用publishProgress(Progress…)方法后,就会在UI线程上回调onProgressUpdate方法</p> <p>注解,表示该方法是在主线程上被调用的,且传入的参数是Progress泛型定义的不定长数组。如果在doInBackground中多次调用了publishProgress方法,那么主线程就会多次回调onProgressUpdate方法。</p> </li>       <li> <p>onPostExecute :表示该方法是在主线程中被调用的。当doInBackgroud方法执行完毕后,就表示任务完成了,doInBackgroud方法的返回值就会作为参数在主线程中传入到onPostExecute方法中,这样就可以在主线程中根据任务的执行结果更新UI。</p> </li>      </ul> </li>    </ol>    <h2><strong>内部实现</strong></h2>    <p>上面讲了那么多,然而都不是重点,现在才刚开始进入主题。AsyncTask其实就是用线程池和和handle实现的!</p>    <ol>     <li> <p>AsyncTask的三个状态</p> <pre>  <code class="language-java">public enum Status {       /**        * Indicates that the task has not been executed yet.        * 还没有执行        */       PENDING,       /**        * Indicates that the task is running.       *  正在执行       */       RUNNING,       /**        * Indicates that {@link AsyncTask#onPostExecute} has finished.        * 执行结束        */       FINISHED,   }</code></pre> </li>     <li> <p>子线程与主线程通讯:(handle)</p> <pre>  <code class="language-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]);//调用onPostExecute 将结果post到主线程                   break;               case MESSAGE_POST_PROGRESS://调用onProgressUpdate更新进度                    result.mTask.onProgressUpdate(result.mData);                   break;           }       }   }  private void finish(Result result) {       if (isCancelled()) {           onCancelled(result);       } else {           onPostExecute(result);       }       mStatus = Status.FINISHED;   }</code></pre> </li>     <li> <p>构造函数</p> <pre>  <code class="language-java">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);//调用doInBackground 在子线程中做一系列的事情               Binder.flushPendingCommands();               return postResult(result);//给InternalHandler发送一个doInBackground任务执行完成的消息           }       };         mFuture = new FutureTask<Result>(mWorker) {           @Override           protected void done() {               try {                   postResultIfNotInvoked(get());//等待mWorker的call方法执行完成               } 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);//如果doInBackground发生异常,则向主线程发送一个null的结果               }           }       };   }</code></pre> </li>     <li> <p>execute(params)最终调用executeOnExecutor</p> <pre>  <code class="language-java">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();//在主线程总调用onPreExecute       mWorker.mParams = params;//mWorker 设置参数       exec.execute(mFuture);//线程池执行futureTask       return this;   }</code></pre> </li>     <li>AsyncTask执行一个task的流程图</li>    </ol>    <p style="text-align:center"><img src="https://simg.open-open.com/show/ba72514e3407da66040b2a197c339e15.png"></p>    <p style="text-align:center">流程图1</p>    <p style="text-align:center"><img src="https://simg.open-open.com/show/08007ece9ed4a7c869ef13c7331b4ac7.png"></p>    <p style="text-align:center">流程图2</p>    <p style="text-align:center"><img src="https://simg.open-open.com/show/a1907f484b3f18e6178be0d061cbfa99.png"></p>    <p style="text-align:center">流程图3</p>    <p style="text-align:center"><img src="https://simg.open-open.com/show/df8debc53b987af3d991275bc0e39217.png"></p>    <p style="text-align:center">流程图4</p>    <p> </p>    <p>来自:http://www.jianshu.com/p/589358898780</p>    <p> </p>