AsyncTask源码分析

目的:AsyncTask异步刚开会加载方法-->然后执行什么方法-->最终会执行什么方法 异步加载只能调一次;
AsyncTask的用法

AsyncTask asyncTask=new AsyncTask(){

          @Override
          protected Void doInBackground(Void... params) {
              //请求网络,耗时操作,运行在Thread中
              return null;
          }

          @Override
          protected void onPreExecute() {
              //一调用就会执行的方法,UI线程中
              super.onPreExecute();
          }

          @Override
          protected void onPostExecute(Void aVoid) {
              super.onPostExecute(aVoid);
              //执行完成后返回的方法,运行在UI线程
          }
      };
      asyncTask.execute();
源码分析

首先看 asyncTask.execute();


public final AsyncTask executeOnExecutor(Executor exec,
         Params... params) {
  //status默认的状态  private volatile Status mStatus = Status.PENDING;所以第一次不会走向这里
     if (mStatus != Status.PENDING) {
         switch (mStatus) {
       //如果是RUNNING或者FINISHED状态则抛出异常
             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)");
         }
     }
   //设置当前状态为RUNNING,这也是为什么只能执行一次
     mStatus = Status.RUNNING;
   //首先会执行该方法
     onPreExecute();

     mWorker.mParams = params;
    //execute是个接口,看mFuture是怎么被赋值的
     exec.execute(mFuture);

     return this;
 }
  //第一次new的时候就会走向这里
  public AsyncTask(@Nullable Looper callbackLooper) {
        mHandler = callbackLooper == null || callbackLooper == Looper.getMainLooper()
            ? getMainHandler()
            : new Handler(callbackLooper);

        mWorker = new WorkerRunnable() {
            public Result call() throws Exception {
                mTaskInvoked.set(true);
                Result result = null;
                try {
                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
                    //子线程中调用doInBackground
                    result = doInBackground(mParams);
                    Binder.flushPendingCommands();
                } catch (Throwable tr) {
                    mCancelled.set(true);
                    throw tr;
                } finally {
                  //最终会调用该方法
                    postResult(result);
                }
                return result;
            }
        };
       //将mWorker设置为callable
        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);
                }
            }
        };
    }

我们可以知道FutureTask实际就是一个Runable,所以直接看run方法我们会发现实际最终调用的

result = c.call();//c实际就是callable而callable实际就是调用WorkerRunnable中的call方法
private Result postResult(Result result) {
        @SuppressWarnings("unchecked")
     //Handler发送消息,切换到主线程
        Message message = getHandler().obtainMessage(MESSAGE_POST_RESULT,
                new AsyncTaskResult(this, result));
        message.sendToTarget();
        return result;
    }

最终会走到这里

   private void finish(Result result) {
        if (isCancelled()) {
        //如果已经取消,调用oncancelled方法
            onCancelled(result);
        } else {
          //主线程调用该方法
            onPostExecute(result);
        }
       //设置状态为FINISHED
        mStatus = Status.FINISHED;
    }

总结:.execute一调用就会判断当前状态如果状态不对就会抛出异常,然后设置状态为RUNNING,然后执行onPreExecute(), 开一个线程执行 doInBackground(), doInBackground()执行完毕之后会利用Handler发送消息切换主线程中,然后执行onPostExecute()方法,最后把状态置为FINISHED。

你可能感兴趣的:(AsyncTask源码分析)