Home | History | Annotate | Download | only in os
      1 /*
      2  * Copyright (C) 2008 The Android Open Source Project
      3  *
      4  * Licensed under the Apache License, Version 2.0 (the "License");
      5  * you may not use this file except in compliance with the License.
      6  * You may obtain a copy of the License at
      7  *
      8  *      http://www.apache.org/licenses/LICENSE-2.0
      9  *
     10  * Unless required by applicable law or agreed to in writing, software
     11  * distributed under the License is distributed on an "AS IS" BASIS,
     12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
     13  * See the License for the specific language governing permissions and
     14  * limitations under the License.
     15  */
     16 
     17 package android.os;
     18 
     19 import java.util.ArrayDeque;
     20 import java.util.concurrent.BlockingQueue;
     21 import java.util.concurrent.Callable;
     22 import java.util.concurrent.CancellationException;
     23 import java.util.concurrent.Executor;
     24 import java.util.concurrent.ExecutionException;
     25 import java.util.concurrent.FutureTask;
     26 import java.util.concurrent.LinkedBlockingQueue;
     27 import java.util.concurrent.ThreadFactory;
     28 import java.util.concurrent.ThreadPoolExecutor;
     29 import java.util.concurrent.TimeUnit;
     30 import java.util.concurrent.TimeoutException;
     31 import java.util.concurrent.atomic.AtomicBoolean;
     32 import java.util.concurrent.atomic.AtomicInteger;
     33 
     34 /**
     35  * <p>AsyncTask enables proper and easy use of the UI thread. This class allows to
     36  * perform background operations and publish results on the UI thread without
     37  * having to manipulate threads and/or handlers.</p>
     38  *
     39  * <p>AsyncTask is designed to be a helper class around {@link Thread} and {@link Handler}
     40  * and does not constitute a generic threading framework. AsyncTasks should ideally be
     41  * used for short operations (a few seconds at the most.) If you need to keep threads
     42  * running for long periods of time, it is highly recommended you use the various APIs
     43  * provided by the <code>java.util.concurrent</code> pacakge such as {@link Executor},
     44  * {@link ThreadPoolExecutor} and {@link FutureTask}.</p>
     45  *
     46  * <p>An asynchronous task is defined by a computation that runs on a background thread and
     47  * whose result is published on the UI thread. An asynchronous task is defined by 3 generic
     48  * types, called <code>Params</code>, <code>Progress</code> and <code>Result</code>,
     49  * and 4 steps, called <code>onPreExecute</code>, <code>doInBackground</code>,
     50  * <code>onProgressUpdate</code> and <code>onPostExecute</code>.</p>
     51  *
     52  * <div class="special reference">
     53  * <h3>Developer Guides</h3>
     54  * <p>For more information about using tasks and threads, read the
     55  * <a href="{@docRoot}guide/topics/fundamentals/processes-and-threads.html">Processes and
     56  * Threads</a> developer guide.</p>
     57  * </div>
     58  *
     59  * <h2>Usage</h2>
     60  * <p>AsyncTask must be subclassed to be used. The subclass will override at least
     61  * one method ({@link #doInBackground}), and most often will override a
     62  * second one ({@link #onPostExecute}.)</p>
     63  *
     64  * <p>Here is an example of subclassing:</p>
     65  * <pre class="prettyprint">
     66  * private class DownloadFilesTask extends AsyncTask&lt;URL, Integer, Long&gt; {
     67  *     protected Long doInBackground(URL... urls) {
     68  *         int count = urls.length;
     69  *         long totalSize = 0;
     70  *         for (int i = 0; i < count; i++) {
     71  *             totalSize += Downloader.downloadFile(urls[i]);
     72  *             publishProgress((int) ((i / (float) count) * 100));
     73  *             // Escape early if cancel() is called
     74  *             if (isCancelled()) break;
     75  *         }
     76  *         return totalSize;
     77  *     }
     78  *
     79  *     protected void onProgressUpdate(Integer... progress) {
     80  *         setProgressPercent(progress[0]);
     81  *     }
     82  *
     83  *     protected void onPostExecute(Long result) {
     84  *         showDialog("Downloaded " + result + " bytes");
     85  *     }
     86  * }
     87  * </pre>
     88  *
     89  * <p>Once created, a task is executed very simply:</p>
     90  * <pre class="prettyprint">
     91  * new DownloadFilesTask().execute(url1, url2, url3);
     92  * </pre>
     93  *
     94  * <h2>AsyncTask's generic types</h2>
     95  * <p>The three types used by an asynchronous task are the following:</p>
     96  * <ol>
     97  *     <li><code>Params</code>, the type of the parameters sent to the task upon
     98  *     execution.</li>
     99  *     <li><code>Progress</code>, the type of the progress units published during
    100  *     the background computation.</li>
    101  *     <li><code>Result</code>, the type of the result of the background
    102  *     computation.</li>
    103  * </ol>
    104  * <p>Not all types are always used by an asynchronous task. To mark a type as unused,
    105  * simply use the type {@link Void}:</p>
    106  * <pre>
    107  * private class MyTask extends AsyncTask&lt;Void, Void, Void&gt; { ... }
    108  * </pre>
    109  *
    110  * <h2>The 4 steps</h2>
    111  * <p>When an asynchronous task is executed, the task goes through 4 steps:</p>
    112  * <ol>
    113  *     <li>{@link #onPreExecute()}, invoked on the UI thread before the task
    114  *     is executed. This step is normally used to setup the task, for instance by
    115  *     showing a progress bar in the user interface.</li>
    116  *     <li>{@link #doInBackground}, invoked on the background thread
    117  *     immediately after {@link #onPreExecute()} finishes executing. This step is used
    118  *     to perform background computation that can take a long time. The parameters
    119  *     of the asynchronous task are passed to this step. The result of the computation must
    120  *     be returned by this step and will be passed back to the last step. This step
    121  *     can also use {@link #publishProgress} to publish one or more units
    122  *     of progress. These values are published on the UI thread, in the
    123  *     {@link #onProgressUpdate} step.</li>
    124  *     <li>{@link #onProgressUpdate}, invoked on the UI thread after a
    125  *     call to {@link #publishProgress}. The timing of the execution is
    126  *     undefined. This method is used to display any form of progress in the user
    127  *     interface while the background computation is still executing. For instance,
    128  *     it can be used to animate a progress bar or show logs in a text field.</li>
    129  *     <li>{@link #onPostExecute}, invoked on the UI thread after the background
    130  *     computation finishes. The result of the background computation is passed to
    131  *     this step as a parameter.</li>
    132  * </ol>
    133  *
    134  * <h2>Cancelling a task</h2>
    135  * <p>A task can be cancelled at any time by invoking {@link #cancel(boolean)}. Invoking
    136  * this method will cause subsequent calls to {@link #isCancelled()} to return true.
    137  * After invoking this method, {@link #onCancelled(Object)}, instead of
    138  * {@link #onPostExecute(Object)} will be invoked after {@link #doInBackground(Object[])}
    139  * returns. To ensure that a task is cancelled as quickly as possible, you should always
    140  * check the return value of {@link #isCancelled()} periodically from
    141  * {@link #doInBackground(Object[])}, if possible (inside a loop for instance.)</p>
    142  *
    143  * <h2>Threading rules</h2>
    144  * <p>There are a few threading rules that must be followed for this class to
    145  * work properly:</p>
    146  * <ul>
    147  *     <li>The AsyncTask class must be loaded on the UI thread. This is done
    148  *     automatically as of {@link android.os.Build.VERSION_CODES#JELLY_BEAN}.</li>
    149  *     <li>The task instance must be created on the UI thread.</li>
    150  *     <li>{@link #execute} must be invoked on the UI thread.</li>
    151  *     <li>Do not call {@link #onPreExecute()}, {@link #onPostExecute},
    152  *     {@link #doInBackground}, {@link #onProgressUpdate} manually.</li>
    153  *     <li>The task can be executed only once (an exception will be thrown if
    154  *     a second execution is attempted.)</li>
    155  * </ul>
    156  *
    157  * <h2>Memory observability</h2>
    158  * <p>AsyncTask guarantees that all callback calls are synchronized in such a way that the following
    159  * operations are safe without explicit synchronizations.</p>
    160  * <ul>
    161  *     <li>Set member fields in the constructor or {@link #onPreExecute}, and refer to them
    162  *     in {@link #doInBackground}.
    163  *     <li>Set member fields in {@link #doInBackground}, and refer to them in
    164  *     {@link #onProgressUpdate} and {@link #onPostExecute}.
    165  * </ul>
    166  *
    167  * <h2>Order of execution</h2>
    168  * <p>When first introduced, AsyncTasks were executed serially on a single background
    169  * thread. Starting with {@link android.os.Build.VERSION_CODES#DONUT}, this was changed
    170  * to a pool of threads allowing multiple tasks to operate in parallel. Starting with
    171  * {@link android.os.Build.VERSION_CODES#HONEYCOMB}, tasks are executed on a single
    172  * thread to avoid common application errors caused by parallel execution.</p>
    173  * <p>If you truly want parallel execution, you can invoke
    174  * {@link #executeOnExecutor(java.util.concurrent.Executor, Object[])} with
    175  * {@link #THREAD_POOL_EXECUTOR}.</p>
    176  */
    177 public abstract class AsyncTask<Params, Progress, Result> {
    178     private static final String LOG_TAG = "AsyncTask";
    179 
    180     private static final int CPU_COUNT = Runtime.getRuntime().availableProcessors();
    181     private static final int CORE_POOL_SIZE = CPU_COUNT + 1;
    182     private static final int MAXIMUM_POOL_SIZE = CPU_COUNT * 2 + 1;
    183     private static final int KEEP_ALIVE = 1;
    184 
    185     private static final ThreadFactory sThreadFactory = new ThreadFactory() {
    186         private final AtomicInteger mCount = new AtomicInteger(1);
    187 
    188         public Thread newThread(Runnable r) {
    189             return new Thread(r, "AsyncTask #" + mCount.getAndIncrement());
    190         }
    191     };
    192 
    193     private static final BlockingQueue<Runnable> sPoolWorkQueue =
    194             new LinkedBlockingQueue<Runnable>(128);
    195 
    196     /**
    197      * An {@link Executor} that can be used to execute tasks in parallel.
    198      */
    199     public static final Executor THREAD_POOL_EXECUTOR
    200             = new ThreadPoolExecutor(CORE_POOL_SIZE, MAXIMUM_POOL_SIZE, KEEP_ALIVE,
    201                     TimeUnit.SECONDS, sPoolWorkQueue, sThreadFactory);
    202 
    203     /**
    204      * An {@link Executor} that executes tasks one at a time in serial
    205      * order.  This serialization is global to a particular process.
    206      */
    207     public static final Executor SERIAL_EXECUTOR = new SerialExecutor();
    208 
    209     private static final int MESSAGE_POST_RESULT = 0x1;
    210     private static final int MESSAGE_POST_PROGRESS = 0x2;
    211 
    212     private static final InternalHandler sHandler = new InternalHandler();
    213 
    214     private static volatile Executor sDefaultExecutor = SERIAL_EXECUTOR;
    215     private final WorkerRunnable<Params, Result> mWorker;
    216     private final FutureTask<Result> mFuture;
    217 
    218     private volatile Status mStatus = Status.PENDING;
    219 
    220     private final AtomicBoolean mCancelled = new AtomicBoolean();
    221     private final AtomicBoolean mTaskInvoked = new AtomicBoolean();
    222 
    223     private static class SerialExecutor implements Executor {
    224         final ArrayDeque<Runnable> mTasks = new ArrayDeque<Runnable>();
    225         Runnable mActive;
    226 
    227         public synchronized void execute(final Runnable r) {
    228             mTasks.offer(new Runnable() {
    229                 public void run() {
    230                     try {
    231                         r.run();
    232                     } finally {
    233                         scheduleNext();
    234                     }
    235                 }
    236             });
    237             if (mActive == null) {
    238                 scheduleNext();
    239             }
    240         }
    241 
    242         protected synchronized void scheduleNext() {
    243             if ((mActive = mTasks.poll()) != null) {
    244                 THREAD_POOL_EXECUTOR.execute(mActive);
    245             }
    246         }
    247     }
    248 
    249     /**
    250      * Indicates the current status of the task. Each status will be set only once
    251      * during the lifetime of a task.
    252      */
    253     public enum Status {
    254         /**
    255          * Indicates that the task has not been executed yet.
    256          */
    257         PENDING,
    258         /**
    259          * Indicates that the task is running.
    260          */
    261         RUNNING,
    262         /**
    263          * Indicates that {@link AsyncTask#onPostExecute} has finished.
    264          */
    265         FINISHED,
    266     }
    267 
    268     /** @hide Used to force static handler to be created. */
    269     public static void init() {
    270         sHandler.getLooper();
    271     }
    272 
    273     /** @hide */
    274     public static void setDefaultExecutor(Executor exec) {
    275         sDefaultExecutor = exec;
    276     }
    277 
    278     /**
    279      * Creates a new asynchronous task. This constructor must be invoked on the UI thread.
    280      */
    281     public AsyncTask() {
    282         mWorker = new WorkerRunnable<Params, Result>() {
    283             public Result call() throws Exception {
    284                 mTaskInvoked.set(true);
    285 
    286                 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
    287                 //noinspection unchecked
    288                 return postResult(doInBackground(mParams));
    289             }
    290         };
    291 
    292         mFuture = new FutureTask<Result>(mWorker) {
    293             @Override
    294             protected void done() {
    295                 try {
    296                     postResultIfNotInvoked(get());
    297                 } catch (InterruptedException e) {
    298                     android.util.Log.w(LOG_TAG, e);
    299                 } catch (ExecutionException e) {
    300                     throw new RuntimeException("An error occured while executing doInBackground()",
    301                             e.getCause());
    302                 } catch (CancellationException e) {
    303                     postResultIfNotInvoked(null);
    304                 }
    305             }
    306         };
    307     }
    308 
    309     private void postResultIfNotInvoked(Result result) {
    310         final boolean wasTaskInvoked = mTaskInvoked.get();
    311         if (!wasTaskInvoked) {
    312             postResult(result);
    313         }
    314     }
    315 
    316     private Result postResult(Result result) {
    317         @SuppressWarnings("unchecked")
    318         Message message = sHandler.obtainMessage(MESSAGE_POST_RESULT,
    319                 new AsyncTaskResult<Result>(this, result));
    320         message.sendToTarget();
    321         return result;
    322     }
    323 
    324     /**
    325      * Returns the current status of this task.
    326      *
    327      * @return The current status.
    328      */
    329     public final Status getStatus() {
    330         return mStatus;
    331     }
    332 
    333     /**
    334      * Override this method to perform a computation on a background thread. The
    335      * specified parameters are the parameters passed to {@link #execute}
    336      * by the caller of this task.
    337      *
    338      * This method can call {@link #publishProgress} to publish updates
    339      * on the UI thread.
    340      *
    341      * @param params The parameters of the task.
    342      *
    343      * @return A result, defined by the subclass of this task.
    344      *
    345      * @see #onPreExecute()
    346      * @see #onPostExecute
    347      * @see #publishProgress
    348      */
    349     protected abstract Result doInBackground(Params... params);
    350 
    351     /**
    352      * Runs on the UI thread before {@link #doInBackground}.
    353      *
    354      * @see #onPostExecute
    355      * @see #doInBackground
    356      */
    357     protected void onPreExecute() {
    358     }
    359 
    360     /**
    361      * <p>Runs on the UI thread after {@link #doInBackground}. The
    362      * specified result is the value returned by {@link #doInBackground}.</p>
    363      *
    364      * <p>This method won't be invoked if the task was cancelled.</p>
    365      *
    366      * @param result The result of the operation computed by {@link #doInBackground}.
    367      *
    368      * @see #onPreExecute
    369      * @see #doInBackground
    370      * @see #onCancelled(Object)
    371      */
    372     @SuppressWarnings({"UnusedDeclaration"})
    373     protected void onPostExecute(Result result) {
    374     }
    375 
    376     /**
    377      * Runs on the UI thread after {@link #publishProgress} is invoked.
    378      * The specified values are the values passed to {@link #publishProgress}.
    379      *
    380      * @param values The values indicating progress.
    381      *
    382      * @see #publishProgress
    383      * @see #doInBackground
    384      */
    385     @SuppressWarnings({"UnusedDeclaration"})
    386     protected void onProgressUpdate(Progress... values) {
    387     }
    388 
    389     /**
    390      * <p>Runs on the UI thread after {@link #cancel(boolean)} is invoked and
    391      * {@link #doInBackground(Object[])} has finished.</p>
    392      *
    393      * <p>The default implementation simply invokes {@link #onCancelled()} and
    394      * ignores the result. If you write your own implementation, do not call
    395      * <code>super.onCancelled(result)</code>.</p>
    396      *
    397      * @param result The result, if any, computed in
    398      *               {@link #doInBackground(Object[])}, can be null
    399      *
    400      * @see #cancel(boolean)
    401      * @see #isCancelled()
    402      */
    403     @SuppressWarnings({"UnusedParameters"})
    404     protected void onCancelled(Result result) {
    405         onCancelled();
    406     }
    407 
    408     /**
    409      * <p>Applications should preferably override {@link #onCancelled(Object)}.
    410      * This method is invoked by the default implementation of
    411      * {@link #onCancelled(Object)}.</p>
    412      *
    413      * <p>Runs on the UI thread after {@link #cancel(boolean)} is invoked and
    414      * {@link #doInBackground(Object[])} has finished.</p>
    415      *
    416      * @see #onCancelled(Object)
    417      * @see #cancel(boolean)
    418      * @see #isCancelled()
    419      */
    420     protected void onCancelled() {
    421     }
    422 
    423     /**
    424      * Returns <tt>true</tt> if this task was cancelled before it completed
    425      * normally. If you are calling {@link #cancel(boolean)} on the task,
    426      * the value returned by this method should be checked periodically from
    427      * {@link #doInBackground(Object[])} to end the task as soon as possible.
    428      *
    429      * @return <tt>true</tt> if task was cancelled before it completed
    430      *
    431      * @see #cancel(boolean)
    432      */
    433     public final boolean isCancelled() {
    434         return mCancelled.get();
    435     }
    436 
    437     /**
    438      * <p>Attempts to cancel execution of this task.  This attempt will
    439      * fail if the task has already completed, already been cancelled,
    440      * or could not be cancelled for some other reason. If successful,
    441      * and this task has not started when <tt>cancel</tt> is called,
    442      * this task should never run. If the task has already started,
    443      * then the <tt>mayInterruptIfRunning</tt> parameter determines
    444      * whether the thread executing this task should be interrupted in
    445      * an attempt to stop the task.</p>
    446      *
    447      * <p>Calling this method will result in {@link #onCancelled(Object)} being
    448      * invoked on the UI thread after {@link #doInBackground(Object[])}
    449      * returns. Calling this method guarantees that {@link #onPostExecute(Object)}
    450      * is never invoked. After invoking this method, you should check the
    451      * value returned by {@link #isCancelled()} periodically from
    452      * {@link #doInBackground(Object[])} to finish the task as early as
    453      * possible.</p>
    454      *
    455      * @param mayInterruptIfRunning <tt>true</tt> if the thread executing this
    456      *        task should be interrupted; otherwise, in-progress tasks are allowed
    457      *        to complete.
    458      *
    459      * @return <tt>false</tt> if the task could not be cancelled,
    460      *         typically because it has already completed normally;
    461      *         <tt>true</tt> otherwise
    462      *
    463      * @see #isCancelled()
    464      * @see #onCancelled(Object)
    465      */
    466     public final boolean cancel(boolean mayInterruptIfRunning) {
    467         mCancelled.set(true);
    468         return mFuture.cancel(mayInterruptIfRunning);
    469     }
    470 
    471     /**
    472      * Waits if necessary for the computation to complete, and then
    473      * retrieves its result.
    474      *
    475      * @return The computed result.
    476      *
    477      * @throws CancellationException If the computation was cancelled.
    478      * @throws ExecutionException If the computation threw an exception.
    479      * @throws InterruptedException If the current thread was interrupted
    480      *         while waiting.
    481      */
    482     public final Result get() throws InterruptedException, ExecutionException {
    483         return mFuture.get();
    484     }
    485 
    486     /**
    487      * Waits if necessary for at most the given time for the computation
    488      * to complete, and then retrieves its result.
    489      *
    490      * @param timeout Time to wait before cancelling the operation.
    491      * @param unit The time unit for the timeout.
    492      *
    493      * @return The computed result.
    494      *
    495      * @throws CancellationException If the computation was cancelled.
    496      * @throws ExecutionException If the computation threw an exception.
    497      * @throws InterruptedException If the current thread was interrupted
    498      *         while waiting.
    499      * @throws TimeoutException If the wait timed out.
    500      */
    501     public final Result get(long timeout, TimeUnit unit) throws InterruptedException,
    502             ExecutionException, TimeoutException {
    503         return mFuture.get(timeout, unit);
    504     }
    505 
    506     /**
    507      * Executes the task with the specified parameters. The task returns
    508      * itself (this) so that the caller can keep a reference to it.
    509      *
    510      * <p>Note: this function schedules the task on a queue for a single background
    511      * thread or pool of threads depending on the platform version.  When first
    512      * introduced, AsyncTasks were executed serially on a single background thread.
    513      * Starting with {@link android.os.Build.VERSION_CODES#DONUT}, this was changed
    514      * to a pool of threads allowing multiple tasks to operate in parallel. Starting
    515      * {@link android.os.Build.VERSION_CODES#HONEYCOMB}, tasks are back to being
    516      * executed on a single thread to avoid common application errors caused
    517      * by parallel execution.  If you truly want parallel execution, you can use
    518      * the {@link #executeOnExecutor} version of this method
    519      * with {@link #THREAD_POOL_EXECUTOR}; however, see commentary there for warnings
    520      * on its use.
    521      *
    522      * <p>This method must be invoked on the UI thread.
    523      *
    524      * @param params The parameters of the task.
    525      *
    526      * @return This instance of AsyncTask.
    527      *
    528      * @throws IllegalStateException If {@link #getStatus()} returns either
    529      *         {@link AsyncTask.Status#RUNNING} or {@link AsyncTask.Status#FINISHED}.
    530      *
    531      * @see #executeOnExecutor(java.util.concurrent.Executor, Object[])
    532      * @see #execute(Runnable)
    533      */
    534     public final AsyncTask<Params, Progress, Result> execute(Params... params) {
    535         return executeOnExecutor(sDefaultExecutor, params);
    536     }
    537 
    538     /**
    539      * Executes the task with the specified parameters. The task returns
    540      * itself (this) so that the caller can keep a reference to it.
    541      *
    542      * <p>This method is typically used with {@link #THREAD_POOL_EXECUTOR} to
    543      * allow multiple tasks to run in parallel on a pool of threads managed by
    544      * AsyncTask, however you can also use your own {@link Executor} for custom
    545      * behavior.
    546      *
    547      * <p><em>Warning:</em> Allowing multiple tasks to run in parallel from
    548      * a thread pool is generally <em>not</em> what one wants, because the order
    549      * of their operation is not defined.  For example, if these tasks are used
    550      * to modify any state in common (such as writing a file due to a button click),
    551      * there are no guarantees on the order of the modifications.
    552      * Without careful work it is possible in rare cases for the newer version
    553      * of the data to be over-written by an older one, leading to obscure data
    554      * loss and stability issues.  Such changes are best
    555      * executed in serial; to guarantee such work is serialized regardless of
    556      * platform version you can use this function with {@link #SERIAL_EXECUTOR}.
    557      *
    558      * <p>This method must be invoked on the UI thread.
    559      *
    560      * @param exec The executor to use.  {@link #THREAD_POOL_EXECUTOR} is available as a
    561      *              convenient process-wide thread pool for tasks that are loosely coupled.
    562      * @param params The parameters of the task.
    563      *
    564      * @return This instance of AsyncTask.
    565      *
    566      * @throws IllegalStateException If {@link #getStatus()} returns either
    567      *         {@link AsyncTask.Status#RUNNING} or {@link AsyncTask.Status#FINISHED}.
    568      *
    569      * @see #execute(Object[])
    570      */
    571     public final AsyncTask<Params, Progress, Result> executeOnExecutor(Executor exec,
    572             Params... params) {
    573         if (mStatus != Status.PENDING) {
    574             switch (mStatus) {
    575                 case RUNNING:
    576                     throw new IllegalStateException("Cannot execute task:"
    577                             + " the task is already running.");
    578                 case FINISHED:
    579                     throw new IllegalStateException("Cannot execute task:"
    580                             + " the task has already been executed "
    581                             + "(a task can be executed only once)");
    582             }
    583         }
    584 
    585         mStatus = Status.RUNNING;
    586 
    587         onPreExecute();
    588 
    589         mWorker.mParams = params;
    590         exec.execute(mFuture);
    591 
    592         return this;
    593     }
    594 
    595     /**
    596      * Convenience version of {@link #execute(Object...)} for use with
    597      * a simple Runnable object. See {@link #execute(Object[])} for more
    598      * information on the order of execution.
    599      *
    600      * @see #execute(Object[])
    601      * @see #executeOnExecutor(java.util.concurrent.Executor, Object[])
    602      */
    603     public static void execute(Runnable runnable) {
    604         sDefaultExecutor.execute(runnable);
    605     }
    606 
    607     /**
    608      * This method can be invoked from {@link #doInBackground} to
    609      * publish updates on the UI thread while the background computation is
    610      * still running. Each call to this method will trigger the execution of
    611      * {@link #onProgressUpdate} on the UI thread.
    612      *
    613      * {@link #onProgressUpdate} will note be called if the task has been
    614      * canceled.
    615      *
    616      * @param values The progress values to update the UI with.
    617      *
    618      * @see #onProgressUpdate
    619      * @see #doInBackground
    620      */
    621     protected final void publishProgress(Progress... values) {
    622         if (!isCancelled()) {
    623             sHandler.obtainMessage(MESSAGE_POST_PROGRESS,
    624                     new AsyncTaskResult<Progress>(this, values)).sendToTarget();
    625         }
    626     }
    627 
    628     private void finish(Result result) {
    629         if (isCancelled()) {
    630             onCancelled(result);
    631         } else {
    632             onPostExecute(result);
    633         }
    634         mStatus = Status.FINISHED;
    635     }
    636 
    637     private static class InternalHandler extends Handler {
    638         @SuppressWarnings({"unchecked", "RawUseOfParameterizedType"})
    639         @Override
    640         public void handleMessage(Message msg) {
    641             AsyncTaskResult result = (AsyncTaskResult) msg.obj;
    642             switch (msg.what) {
    643                 case MESSAGE_POST_RESULT:
    644                     // There is only one result
    645                     result.mTask.finish(result.mData[0]);
    646                     break;
    647                 case MESSAGE_POST_PROGRESS:
    648                     result.mTask.onProgressUpdate(result.mData);
    649                     break;
    650             }
    651         }
    652     }
    653 
    654     private static abstract class WorkerRunnable<Params, Result> implements Callable<Result> {
    655         Params[] mParams;
    656     }
    657 
    658     @SuppressWarnings({"RawUseOfParameterizedType"})
    659     private static class AsyncTaskResult<Data> {
    660         final AsyncTask mTask;
    661         final Data[] mData;
    662 
    663         AsyncTaskResult(AsyncTask task, Data... data) {
    664             mTask = task;
    665             mData = data;
    666         }
    667     }
    668 }
    669