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