Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲
 Android教程網 >> Android技術 >> 關於Android編程 >> Android AsyncTask實現機制詳細介紹及實例代碼

Android AsyncTask實現機制詳細介紹及實例代碼

編輯:關於Android編程

Android AsyncTask實現機制

示例代碼:

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

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

execute先調用onPreExecute()(可見,onPreExecute是自動調用的)然後調用exec.execute(mFuture)

 public interface Executor {
    void execute(Runnable command);
  }

這是一個接口,具體實現在

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

從上面可知,AsyncTask執行過程如下:先執行onPreExecute,然後交給SerialExecutor執行。在SerialExecutor中,先把Runnable添加到mTasks中。

如果沒有Runnable正在執行,那麼就調用SerialExecutor的scheduleNext。同時當一個Runnable執行完以後,繼續執行下一個任務

AsyncTask中有兩個線程池,THREAD_POOL_EXECUTOR和SERIAL_EXECUTOR,以及一個Handler–InternalHandler

 /**
   * An {@link Executor} that can be used to execute tasks in parallel.
   */
  public static final Executor THREAD_POOL_EXECUTOR
      = new ThreadPoolExecutor(CORE_POOL_SIZE, MAXIMUM_POOL_SIZE, KEEP_ALIVE,
          TimeUnit.SECONDS, sPoolWorkQueue, sThreadFactory);

  /**
   * An {@link Executor} that executes tasks one at a time in serial
   * order. This serialization is global to a particular process.
   */
  public static final Executor SERIAL_EXECUTOR = new SerialExecutor();

  private static InternalHandler sHandler;

SERIAL_EXECUTOR用於任務的排列,THREAD_POOL_EXECUTOR真正執行線程,InternalHandler用於線程切換
先看構造函數

  public AsyncTask() {
    mWorker = new WorkerRunnable<Params, Result>() {
      public Result call() throws Exception {
        mTaskInvoked.set(true);

        Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
        //noinspection unchecked
        return postResult(doInBackground(mParams));
      }
    };

    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 occured while executing doInBackground()",
              e.getCause());
        } catch (CancellationException e) {
          postResultIfNotInvoked(null);
        }
      }
    };
  }

看到了熟悉的doInBackground了吧,然後調用postResult

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

主線程中創建InternalHandler並發送MESSAGE_POST_RESULT消息,然後調用finish函數

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

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

finish中調用onPostExecute。

AsyncTask工作流程:new MyThread().execute(1);

先構造函數,然後execute

構造函數只是准備了mWorker和mFuture這兩個變量

execute中調用onPreExecute,然後exec.execute(mFuture),其中響應了call函數,call中調用doInBackground,然後將結果傳給Handler然後finish掉,finish函數調用onPostExecute

你可能會奇怪,為什麼沒有onProgressUpdate,有注解可以解釋

 /**
   * Runs on the UI thread after {@link #publishProgress} is invoked.
   * The specified values are the values passed to {@link #publishProgress}.
   *
   * @param values The values indicating progress.
   *
   * @see #publishProgress
   * @see #doInBackground
   */
  @SuppressWarnings({"UnusedDeclaration"})
  protected void onProgressUpdate(Progress... values) {
  }

也就是說必須調用publishProgress才會自動調用onProgressUpdate。
那如何調用publishProgress呢?

 /**
   * Override this method to perform a computation on a background thread. The
   * specified parameters are the parameters passed to {@link #execute}
   * by the caller of this task.
   *
   * This method can call {@link #publishProgress} to publish updates
   * on the UI thread.
   *
   * @param params The parameters of the task.
   *
   * @return A result, defined by the subclass of this task.
   *
   * @see #onPreExecute()
   * @see #onPostExecute
   * @see #publishProgress
   */
  protected abstract Result doInBackground(Params... params);

doInBackground說的很明確,在doInBackground函數裡面顯示調用publishProgress即可。

publishProgress源碼:

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

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

感謝閱讀,希望能幫助到大家,謝謝大家對本站的支持!

  1. 上一頁:
  2. 下一頁:
熱門文章
閱讀排行版
Copyright © Android教程網 All Rights Reserved