欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

Android AsyncTask實(shí)現(xiàn)機(jī)制詳細(xì)介紹及實(shí)例代碼

 更新時(shí)間:2016年12月20日 16:39:58   投稿:lqh  
這篇文章主要介紹了Android AsyncTask實(shí)現(xiàn)機(jī)制詳細(xì)介紹及實(shí)例代碼的相關(guān)資料,這里附有示例代碼,幫助大家學(xué)習(xí)理解,需要的朋友可以參考下

Android AsyncTask實(shí)現(xiàn)機(jī)制

示例代碼:

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先調(diào)用onPreExecute()(可見,onPreExecute是自動(dòng)調(diào)用的)然后調(diào)用exec.execute(mFuture)

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

這是一個(gè)接口,具體實(shí)現(xiàn)在

 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執(zhí)行過程如下:先執(zhí)行onPreExecute,然后交給SerialExecutor執(zhí)行。在SerialExecutor中,先把Runnable添加到mTasks中。

如果沒有Runnable正在執(zhí)行,那么就調(diào)用SerialExecutor的scheduleNext。同時(shí)當(dāng)一個(gè)Runnable執(zhí)行完以后,繼續(xù)執(zhí)行下一個(gè)任務(wù)

AsyncTask中有兩個(gè)線程池,THREAD_POOL_EXECUTOR和SERIAL_EXECUTOR,以及一個(gè)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用于任務(wù)的排列,THREAD_POOL_EXECUTOR真正執(zhí)行線程,InternalHandler用于線程切換
先看構(gòu)造函數(shù)

  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了吧,然后調(diào)用postResult

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

主線程中創(chuàng)建InternalHandler并發(fā)送MESSAGE_POST_RESULT消息,然后調(diào)用finish函數(shù)

 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中調(diào)用onPostExecute。

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

先構(gòu)造函數(shù),然后execute

構(gòu)造函數(shù)只是準(zhǔn)備了mWorker和mFuture這兩個(gè)變量

execute中調(diào)用onPreExecute,然后exec.execute(mFuture),其中響應(yīng)了call函數(shù),call中調(diào)用doInBackground,然后將結(jié)果傳給Handler然后finish掉,finish函數(shù)調(diào)用onPostExecute

你可能會(huì)奇怪,為什么沒有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) {
  }

也就是說(shuō)必須調(diào)用publishProgress才會(huì)自動(dòng)調(diào)用onProgressUpdate。
那如何調(diào)用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說(shuō)的很明確,在doInBackground函數(shù)里面顯示調(diào)用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:
          //****************************************在這里調(diào)用
          result.mTask.onProgressUpdate(result.mData);
          break;
      }
    }
  }

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

相關(guān)文章

最新評(píng)論