AsyncTask源码翻译

来源:互联网 发布:淘宝卡 哪个好 编辑:程序博客网 时间:2024/05/16 12:06
前言:/**  <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 <code>java.util.concurrent</code> 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 <code>Params</code>, <code>Progress</code> and <code>Result</code>,and 4 steps, called<code>onPreExecute</code>, <code>doInBackground</code>, <code>onProgressUpdate</code> and <code>onPostExecute</code>.</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>译文:一次被创建,一个任务将会执行的非常简单(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><code>Params</code>, the type of the parameters sent to the task upon   execution.</li> 译文:Params,是执行任务时发送的参数类型。    <li><code>Progress</code>, the type of the progress units published during   the background computation.</li> 译文:Progress,是后台计算过程中的进度单元类型。     <li><code>Result</code>, 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     * <code>super.onCancelled(result)</code>.</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;        }    }}
0 0
原创粉丝点击