AsyncTask源代码翻译
阅读原文时间:2023年07月10日阅读:2
前言:
/**
  <p>AsyncTask enables proper and easy use of the UI thread. This class allows to perform background operations and publish results on the UI thread without  having to manipulate threads and/or handlers.</p>

 译文:AsyncTask的正确实现。易于使用的用户界面线程。此类同意运行后台操作并把结果公布在UI线程上(主线程)而且使用handler.

 * <p>AsyncTask is designed to be a helper class around {@link Thread} and {@link Handler} and does not constitute a generic threading framework. AsyncTasks should ideally be used for short operations (a few seconds at the most.) If you need to keep threads  running for long periods of time, it is highly recommended you use the various APIs
 provided by the java.util.concurrent package such as {@link Executor},{@link ThreadPoolExecutor} and {@link FutureTask}.</p>

 译文:异步任务帮助类的设计是环绕着线程和Handler的。可是并不构成通用线程的框架,异步任务应该用于非常短的时间操作(几秒钟),假设你须要保持线程运行非常长一段时间的话,你须要查看其它的各种api.

  <p>An asynchronous task is defined by a computation that runs on a background thread and whose result is published on the UI thread. An asynchronous task is defined by 3 generic types, called Params, Progress and Result,and 4 steps, calledonPreExecute, doInBackground, onProgressUpdate and onPostExecute.</p>

译文:一个异步任务由在后台线程运行的计算,其结果传给UI线程上。

一个异步任务由3泛型类型定义。名为PARAMS,Progress和Result。和4个步骤。名为 onPreExecute(准备阶段),doInBackground(运行阶段),onProgressUpdate(进度更新阶段)和 onPostExecute(运行完毕阶段)。

 <div class="special reference">
  <h3>Developer Guides</h3>
  <p>For more information about using tasks and threads, read the
 <a href="{@docRoot}guide/topics/fundamentals/processes-and-threads.html">Processes and
 Threads</a> developer guide.</p> </div>

 译文:特别參考开发人员手冊。很多其它关于任务和线程的请阅读

{@docRoot}guide/topics/fundamentals/processes-and-threads.html进程和线程开发人员引导。
  <p>AsyncTask must be subclassed to be used. The subclass will override at least one method ({@link #doInBackground}), and most often will override a second one ({@link #onPostExecute}.)</p><p>Here is an example of subclassing:</p><pre class="prettyprint">

 * 译文:异步任务必须被子类继承而且必须实现至少一种方法(doInBackground)而且大多数将会覆盖另外一种方法(onPostExecute)这里有一个样例例如以下:

 private class DownloadFilesTask extends AsyncTask&lt;URL, Integer, Long&gt; {
      protected Long doInBackground(URL... urls) {
        int count = urls.length;
        long totalSize = 0;
        for (int i = 0; i < count; i++) {
            totalSize += Downloader.downloadFile(urls[i]);
            publishProgress((int) ((i / (float) count) * 100));
             // Escape early if cancel() is called
              if (isCancelled()) break;
         }
         return totalSize;
     }
    protected void onProgressUpdate(Integer... progress) {
         setProgressPercent(progress[0]);
     }
     protected void onPostExecute(Long result) {
       showDialog("Downloaded " + result + " bytes");
      }
  }
  </pre>  <p>Once created, a task is executed very simply:</p><pre class="prettyprint"> new DownloadFilesTask().execute(url1, url2, url3); </pre>

译文:一次被创建,一个任务将会运行的非常easy
(new DownloadFilesTask().execute(url1, url2, url3));
  <h2>AsyncTask's generic types</h2> <p>The three types used by an asynchronous task are the following:</p>
 译文:异步任务的通用类型这里有三种被异步任务使用以下就是:
 <ol>  <li>Params, the type of the parameters sent to the task upon   execution.</li>
 译文:Params,是运行任务时发送的參数类型。
    <li>Progress, the type of the progress units published during   the background computation.</li>
 译文:Progress,是后台计算过程中的进度单元类型。
     <li>Result, the type of the result of the background  computation.</li></ol>
  译文:Result,是后台线程计算得到结果的类型。

<p>Not all types are always used by an asynchronous task. To mark a type as unused,simply use the type {@link Void}
  译文:不是全部类型都被一个异步任务使用。

要标记为未使用的类型。仅仅需使用该类型
 * private class MyTask extends AsyncTask&lt;Void, Void, Void&gt; { ... }
 * <h2>The 4 steps</h2>
 * <p>When an asynchronous task is executed, the task goes through 4 steps:</p>译文:当一个异步任务被运行时。任务就通过4个步骤来完毕
 *     <li>{@link #onPreExecute()}, invoked on the UI thread before the task   is executed. This step is normally used to setup the task, for instance by    showing a progress bar in the user interface.</li>
 译文:onPreExecute()在任务运行前,在用户界面上调用线程。这一步通经常使用于设置任务,比如通过在用户界面显示一个进度条。

*     <li>{@link #doInBackground}, invoked on the background thread   immediately after {@link #onPreExecute()} finishes executing. This step is used   to perform background computation that can take a long time. The parameters     of the asynchronous task are passed to this step. The result of the computation must    be returned by this step and will be passed back to the last step. This step  can also use {@link #publishProgress} to publish one or more units    of progress. These values are published on the UI thread, in the {@link #onProgressUpdate} step.</li>
 译文:在onPreExecute()运行完后在后台线程上调用,这一步是用来运行后台耗时操作,可能耗费非常长时间。异步任务的完毕的结果必须返回在这一步,并将被传递到最后一步。这一步还能够使用publishProgress()这种方法吧进度传送给UI线程在,onProgressUpdate()这一步
    <li>{@link #onProgressUpdate}, invoked on the UI thread after a    call to {@link #publishProgress}. The timing of the execution is     undefined. This method is used to display any form of progress in the user    interface while the background computation is still executing. For instance,     it can be used to animate a progress bar or show logs in a text field.</li>
  译文:onProgressUpdate(),被UI线程调用在publishProgress这种方法之后。运行的时间是不确定的,这种方法被用来展示进度信息给用户。而后台任然在运行。建议实例它可用于在文本字段中动画一个进度条或显示日志。

<li>{@link #onPostExecute}, invoked on the UI thread after the background computation finishes. The result of the background computation is passed to    this step as a parameter.</li> </ol>
 译文:调用UI线程完毕之后。后台结果被传递到这一步。
  <h2>Cancelling a task</h2><p>A task can be cancelled at any time by invoking {@link #cancel(boolean)}. Invoking this method will cause subsequent calls to {@link #isCancelled()} to return true. After invoking this method, {@link #onCancelled(Object)}, instead of {@link #onPostExecute(Object)} will be invoked after {@link #doInBackground(Object[])} returns. To ensure that a task is cancelled as quickly as possible, you should always check the return value of {@link #isCancelled()} periodically from{@link #doInBackground(Object[])}, if possible (inside a loop for instance.)</p>
 译文:一个任务能被运行取消在随意一时刻,运行这种方法将随后会调用isCancelled()这种方法返回true,之后运行onCancelled(Object)。而不是onPostExecute(Object)。之后将会运行doInBackground(Object[])} 的返回,确保任务尽可能的高速被取消。你应该总是检查isCancelled()的返回值定期doInBackground(Object[])假设可能的话。
  <h2>Threading rules</h2>
 <p>There are a few threading rules that must be followed for this class to work properly:</p>
 译文:有几个线程规则,必须遵循这个类工作。

<ul>     <li>The AsyncTask class must be loaded on the UI thread. This is done  automatically as of {@link android.os.Build.VERSION_CODES#JELLY_BEAN}.</li>
  <li>The task instance must be created on the UI thread.</li>    <li>{@link #execute} must be invoked on the UI thread.</li>    <li>Do not call {@link #onPreExecute()}, {@link #onPostExecute},  {@link #doInBackground}, {@link #onProgressUpdate} manually.</li>
 <li>The task can be executed only once (an exception will be thrown if  a second execution is attempted.)</li></ul>
 译文:AsyncTask必须载入在UI线程。

这是android.os.Build.VERSION_CODES自己主动完毕的。异步任务的实例必须创建在UI线程,不能手动调用onPreExecute(),onPostExecute,doInBackground,  onProgressUpdate。

<h2>Memory observability</h2> <p>AsyncTask guarantees that all callback calls are synchronized in such a way that the following operations are safe without explicit synchronizations.</p>
 译文:AsyncTask的保证全部回调调用以这种方式,以下的操作都没有明白的同步安全同步。

<ul>
  <li>Set member fields in the constructor or {@link #onPreExecute}, and refer to them    in {@link #doInBackground}.<li>Set member fields in {@link #doInBackground}, and refer to them in   {@link #onProgressUpdate} and {@link #onPostExecute}.
 </ul>
 译文:设置属性在构造函数里,或者onPreExecute(),并引用他们在doInBackground,设置成员属性在doInBackground,引用他们在onProgressUpdate和onPostExecute。
  <h2>Order of execution</h2> <p>When first introduced, AsyncTasks were executed serially on a single background thread. Starting with {@link android.os.Build.VERSION_CODES#DONUT}, this was changed to a pool of threads allowing multiple tasks to operate in parallel. Starting with {@link android.os.Build.VERSION_CODES#HONEYCOMB}, tasks are executed on a single thread to avoid common application errors caused by parallel execution.</p><p>If you truly want parallel execution, you can invoke{@link #executeOnExecutor(java.util.concurrent.Executor, Object[])} with
  {@link #THREAD_POOL_EXECUTOR}.</p>
 译文:当第一次推出,AsyncTasks是在一个后台线程运行,这被改为同意线程多任务并行操作的线程池同意多任务操作。任务是在单个线程中运行。以避免因并行运行常见的应用程序错误。假设你真正想要并行运行,你能够调java.util.concurrent.Executor类。



public abstract class AsyncTask<Params, Progress, Result> {
    private static final String LOG_TAG = "AsyncTask";
    private static final int CPU_COUNT = Runtime.getRuntime().availableProcessors();
    //返回CPU可利用的处理器核心数。至少为1
    private static final int CORE_POOL_SIZE = CPU_COUNT + 1;  //线程池长度为核心数+1
    private static final int MAXIMUM_POOL_SIZE = CPU_COUNT * 2 + 1;
    //最大线程池为2倍核心数+1
    private static final int KEEP_ALIVE = 1;

    private static final ThreadFactory sThreadFactory = new ThreadFactory() {
        private final AtomicInteger mCount = new AtomicInteger(1);

        public Thread newThread(Runnable r) {
            return new Thread(r, "AsyncTask #" + mCount.getAndIncrement());
        }
    };

    private static final BlockingQueue<Runnable> sPoolWorkQueue =
            new LinkedBlockingQueue<Runnable>(128);

    /**
     * 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 final int MESSAGE_POST_RESULT = 0x1;
    private static final int MESSAGE_POST_PROGRESS = 0x2;

    private static final InternalHandler sHandler = new InternalHandler();

    private static volatile Executor sDefaultExecutor = SERIAL_EXECUTOR;
    private final WorkerRunnable<Params, Result> mWorker;
    private final FutureTask<Result> mFuture;

    private volatile Status mStatus = Status.PENDING;

    private final AtomicBoolean mCancelled = new AtomicBoolean();
    private final AtomicBoolean mTaskInvoked = new AtomicBoolean();

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

    /**
     * Indicates the current status of the task. Each status will be set only once 指示任务的当前状态。每一个状态将被设置一次
     * during the lifetime of a task. 在一个任务生命周期内
     */
    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.   表明AsyncTask的onPostExecute}已完毕。
         */
        FINISHED,
    }

    /*  一个静态的handler将会被创建
    * @hide Used to force static handler to be created.
*/
    public static void init() {
        sHandler.getLooper();
    }

    /** @hide */
    public static void setDefaultExecutor(Executor exec) {
        sDefaultExecutor = exec;
    }

    /**
     * Creates a new asynchronous task. This constructor must be invoked on the UI thread.  创建一个异步任务,这个构造函数必须在UI线程中被调用
     */
    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);
                }
            }
        };
    }

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

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

    /**
     * Returns the current status of this task.
     *  返回任务的当前状态
     * @return The current status.
     */
    public final Status getStatus() {
        return mStatus;
    }

    /**
     * Override this method to perform a computation on a background thread. The   这种方法是指一个在后台运行的线程
     * specified parameters are the parameters passed to {@link #execute}   指定的參数将被传递给execute方法通过这个任务调用
     * by the caller of this task.
     *
     * This method can call {@link #publishProgress} to publish updates  这种方法将会调用publishProgress方法去刷新进度在UI线程
     * 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);

    /**
     * Runs on the UI thread before {@link #doInBackground}. onPreExecute方法在运行doInBackground之前运行在UI线程
     *
     * @see #onPostExecute
     * @see #doInBackground
     */
    protected void onPreExecute() {
    }

    /**
     * <p>Runs on the UI thread after {@link #doInBackground}. The    在doInBackground方法运行以后运行在UI线程
     * specified result is the value returned by {@link #doInBackground}.</p> 指定结果的值将会在doInBackground方法返回
     *
     * <p>This method won't be invoked if the task was cancelled.</p>    假设任务被取消了的话这种方法将不会被调用
     *
     * @param result The result of the operation computed by {@link #doInBackground}.  这个result 參数是doInBackground这一步计算的结果。

*
     * @see #onPreExecute
     * @see #doInBackground
     * @see #onCancelled(Object)
     */
    @SuppressWarnings({"UnusedDeclaration"})
    protected void onPostExecute(Result result) {
    }

    /**
     * Runs on the UI thread after {@link #publishProgress} is invoked.  publishProgress方法调用之后这种方法就会在UI线程运行
     * The specified values are the values passed to {@link #publishProgress}. values 是publishProgress中计算得到的值
     *
     * @param values The values indicating progress.
     *   values 是一个任务运行的进度
     * @see #publishProgress
     * @see #doInBackground
     */
    @SuppressWarnings({"UnusedDeclaration"})
    protected void onProgressUpdate(Progress... values) {
    }

    /**
     * <p>Runs on the UI thread after {@link #cancel(boolean)} is invoked and
     * {@link #doInBackground(Object[])} has finished.</p>
     * 在cancel被运行,#doInBackground(Object[])已经运行完毕之后这种方法将会在UI线程被调用。
     * <p>The default implementation simply invokes {@link #onCancelled()} and
     * ignores the result. If you write your own implementation, do not call
     * super.onCancelled(result).</p>
     *  默认被简单的调用而且忽略结果假设你想自己实现这种方法,那么不要调用super.onCancelled(result)这段代码
     * @param result The result, if any, computed in
     *               {@link #doInBackground(Object[])}, can be null
     * result结果可能是不论什么值。来自于#doInBackground(Object[])的计算。可能是null值
     * @see #cancel(boolean)
     * @see #isCancelled()
     */
    @SuppressWarnings({"UnusedParameters"})
    protected void onCancelled(Result result) {
        onCancelled();
    }    

    /**
     * <p>Applications should preferably override {@link #onCancelled(Object)}.
     * This method is invoked by the default implementation of
     * {@link #onCancelled(Object)}.</p>
     *   应用应该最好覆盖onCancelled方法这种方法调用通过实现onCancelled(Object)在#cancel(boolean)运行之后而且doInBackground(Object[])} has finished运行完毕后他将会运行在UI线程
     * <p>Runs on the UI thread after {@link #cancel(boolean)} is invoked and
     * {@link #doInBackground(Object[])} has finished.</p>
     *
     * @see #onCancelled(Object)
     * @see #cancel(boolean)
     * @see #isCancelled()
     */
    protected void onCancelled() {
    }

    /**
     * Returns <tt>true</tt> if this task was cancelled before it completed
     * normally. If you are calling {@link #cancel(boolean)} on the task,
     * the value returned by this method should be checked periodically from
     * {@link #doInBackground(Object[])} to end the task as soon as possible.
     * 假设这个任务被取消了在它正常完毕之前,isCancelled将会返回true,假设你调用cancel(boolean)在任务中,值被返回通过这种方法(doInBackground(Object[]))应该最好被尽可能的被检查一遍
     * @return <tt>true</tt> if task was cancelled before it completed
     *
     * @see #cancel(boolean)
     */
    public final boolean isCancelled() {
        return mCancelled.get();
    }

    /**
     * <p>Attempts to cancel execution of this task.  This attempt will  试图取消对此任务的运行。这个尝试将会失败
     * fail if the task has already completed, already been cancelled, 假设这个任务已经被完毕或者已经取消或者因为某些原因不能被取消
     * or could not be cancelled for some other reason. If successful, 假设成功
     * and this task has not started when <tt>cancel</tt> is called, 这个任务还未被開始调用
     * this task should never run. If the task has already started, 这个任务就将绝不会运行,假设任务已经開始了这时
     * then the <tt>mayInterruptIfRunning</tt> parameter determines
     * whether the thread executing this task should be interrupted in
     * an attempt to stop the task.</p>
     * 是否运行此任务的线程应该以试图停止任务被中断
     * <p>Calling this method will result in {@link #onCancelled(Object)} being 调用这种方法将导致onCancelled(Object)运行在UI线程当doInBackground(Object[]返回后
     * invoked on the UI thread after {@link #doInBackground(Object[])}
     * returns. Calling this method guarantees that {@link #onPostExecute(Object)}调用这种方法要保证onPostExecute从来没被运行
     * is never invoked. After invoking this method, you should check the 。
     * value returned by {@link #isCancelled()} periodically from
     * {@link #doInBackground(Object[])} to finish the task as early as
     * possible.</p>
     *在运行这种方法时。你应该检查isCancelled返回的值,定期的从doInBackground完毕任务尽可能的早
     * @param mayInterruptIfRunning <tt>true</tt> if the thread executing this
     *        task should be interrupted; otherwise, in-progress tasks are allowed
     *        to complete.
     *假设运行此任务的线程应该被中断;否则。在正在进行的任务被同意完毕。

* @return <tt>false</tt> if the task could not be cancelled,
     *         typically because it has already completed normally;     假设任务不能被取消,一般是因为它已经正常完毕
     *         <tt>true</tt> otherwise
     *
     * @see #isCancelled()
     * @see #onCancelled(Object)
     */
    public final boolean cancel(boolean mayInterruptIfRunning) {
        mCancelled.set(true);
        return mFuture.cancel(mayInterruptIfRunning);
    }

    /**
     * Waits if necessary for the computation to complete, and then
     * retrieves its result.
     *如有必要。等待计算完毕,然后获取其结果。

* @return The computed result.
     *
     * @throws CancellationException If the computation was cancelled.  假设计算被取消将会抛出CancellationException 异常
     * @throws ExecutionException If the computation threw an exception. 假设计算抛出异常将会抛出ExecutionException 异常
     * @throws InterruptedException If the current thread was interrupted
     *         while waiting.
     *   假设当前线程被中断将会抛出InterruptedException 异常。
     */
    public final Result get() throws InterruptedException, ExecutionException {
        return mFuture.get();
    }

    /**
     * Waits if necessary for at most the given time for the computation
     * to complete, and then retrieves its result.
     * 如有必要,等待至多给定的时间计算完毕,然后获取其结果。
     * @param timeout Time to wait before cancelling the operation. 取消操作之前的等待时间
     * @param unit The time unit for the timeout.
     *超时时间单位
     * @return The computed result.
     * 完毕的结果
     * @throws CancellationException If the computation was cancelled.
     * @throws ExecutionException If the computation threw an exception.
     * @throws InterruptedException If the current thread was interrupted
     *         while waiting.
     * @throws TimeoutException If the wait timed out.
     */
    public final Result get(long timeout, TimeUnit unit) throws InterruptedException,
            ExecutionException, TimeoutException {
        return mFuture.get(timeout, unit);
    }

    /**
     * Executes the task with the specified parameters. The task returns 运行指定的參数的任务。

任务返回
     * itself (this) so that the caller can keep a reference to it. 本身(这一点)。使主叫方能够保持对它的引用
     *
     * <p>Note: this function schedules the task on a queue for a single background
     * thread or pool of threads depending on the platform version. 此功能的任务进度为单个后台线程队列或线程池队列的任务取决于平台版本号的。

*  When first introduced, AsyncTasks were executed serially on a single background thread.
     * 当第一次介绍时。异步任务是运行在后来的一系列线程開始于android.os.Build.VERSION_CODES#DONUT
     * Starting with {@link android.os.Build.VERSION_CODES#DONUT}, this was changed
     * to a pool of threads allowing multiple tasks to operate in parallel. Starting 这次将会改变为一个线程池同意多个任务并行地操作
     * {@link android.os.Build.VERSION_CODES#HONEYCOMB}, tasks are back to being  executed on a single thread to avoid common application errors caused  by parallel execution.  If you truly want parallel execution, you can use the {@link #executeOnExecutor} version of this method
     * with {@link #THREAD_POOL_EXECUTOR}; however, see commentary there for warnings
     * on its use.
     *任务曾经是被运行在一个单线程避免并行运行造成共同的应用错误,假设你真的想并行运行你能够使用executeOnExecutor版本号的这种方法然后看到凝视那里是有警告的当使用的时候
     * <p>This method must be invoked on the UI thread.
     *这种方法必须运行在UI线程
     * @param params The parameters of the task.
     *
     * @return This instance of AsyncTask.
     *
     * @throws IllegalStateException If {@link #getStatus()} returns either
     *         {@link AsyncTask.Status#RUNNING} or {@link AsyncTask.Status#FINISHED}.
     *
     * @see #executeOnExecutor(java.util.concurrent.Executor, Object[])
     * @see #execute(Runnable)
     */
    public final AsyncTask<Params, Progress, Result> execute(Params... params) {
        return executeOnExecutor(sDefaultExecutor, params);
    }

    /**
     * Executes the task with the specified parameters. The task returns itself (this) so that the caller can keep a reference to it.  使用指定的參数运行这个任务。任务将会返回它本身。以至于调用者能够对它保持一个引用。

* <p>This method is typically used with {@link #THREAD_POOL_EXECUTOR} to  allow multiple tasks to run in parallel on a pool of threads managed by AsyncTask, however you can also use your own {@link Executor} for custom 这种方法通常被使用多任务同意多个任务并行由管理线程池运行AsyncTask可是你也能够用你自己的Executor定制。
     * behavior.
     *
     * <p><em>Warning:</em> Allowing multiple tasks to run in parallel from a thread pool is generally <em>not</em> what one wants, because the order of their operation is not defined.  For example, if these tasks are used to modify any state in common (such as writing a file due to a button click),
     * 警告:同意多个任务并行的线程池中运行一般的没有想要的东西之中的一个,因为其操作的顺序未定义。比如,假设这些任务是用来改动不论什么状态常见(如写入文件,因为一个按钮点击)
      there are no guarantees on the order of the modifications.Without careful work it is possible in rare cases for the newer version of the data to be over-written by an older one, leading to obscure data loss and stability issues.  Such changes are best executed in serial; to guarantee such work is serialized regardless of platform version you can use this function with {@link #SERIAL_EXECUTOR}.
     *有改动的顺序没有保证,假设没有仔细的工作有可能在极少数情况下对数据的新版本号将超过撰写的一老一,导致模糊的数据丢失和稳定性问题。这种变化是最好的串行运行,保证此项工作的系列化,不管平台版本号,您能够使用此功能
     * <p>This method must be invoked on the UI thread.
     *这种方法将会被运行在UI线程
     * @param exec The executor to use.  {@link #THREAD_POOL_EXECUTOR} is available as a
     *              convenient process-wide thread pool for tasks that are loosely coupled.
     * @param params The parameters of the task.
     *
     * @return This instance of AsyncTask.
     *
     * @throws IllegalStateException If {@link #getStatus()} returns either
     *         {@link AsyncTask.Status#RUNNING} or {@link AsyncTask.Status#FINISHED}.
     *
     * @see #execute(Object[])
     */
    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;
    }

    /**
     * Convenience version of {@link #execute(Object...)} for use with a simple Runnable object. See {@link #execute(Object[])} for more information on the order of execution.
     *方便版{@link#execute(对象...)}为一个简单的Runnable对象使用。见{@link#execute(对象[])}的运行顺序的很多其它信息
     * @see #execute(Object[])
     * @see #executeOnExecutor(java.util.concurrent.Executor, Object[])
     */
    public static void execute(Runnable runnable) {
        sDefaultExecutor.execute(runnable);
    }

    /**
     * This method can be invoked from {@link #doInBackground} to  这种方法将会被运行从doInBackground刷新进度在UI线程,而后台计算是一直在运行的
     * publish updates on the UI thread while the background computation is still running. Each call to this method will trigger the execution of
     * {@link #onProgressUpdate} on the UI thread.
     *每次调用此方法将触发运行onProgressUpdate在UI线程
     * {@link #onProgressUpdate} will not be called if the task has been canceled.
     *onProgressUpdate将不被调用,假设该任务已被取消。
     * @param values The progress values to update the UI with.
     *
     * @see #onProgressUpdate
     * @see #doInBackground
     */
    protected final void publishProgress(Progress... values) {
        if (!isCancelled()) {
            sHandler.obtainMessage(MESSAGE_POST_PROGRESS,
                    new AsyncTaskResult<Progress>(this, values)).sendToTarget();
        }
    }

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

    private static class InternalHandler extends Handler {
        @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 static abstract class WorkerRunnable<Params, Result> implements Callable<Result> {
        Params[] mParams;
    }

    @SuppressWarnings({"RawUseOfParameterizedType"})
    private static class AsyncTaskResult<Data> {
        final AsyncTask mTask;
        final Data[] mData;

        AsyncTaskResult(AsyncTask task, Data... data) {
            mTask = task;
            mData = data;
        }
    }
}

手机扫一扫

移动阅读更方便

阿里云服务器
腾讯云服务器
七牛云服务器

你可能感兴趣的文章