• 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 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> package 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 volatile Executor sDefaultExecutor = SERIAL_EXECUTOR;
213     private static InternalHandler sHandler;
214 
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 
execute(final Runnable r)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 
scheduleNext()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 
getHandler()268     private static Handler getHandler() {
269         synchronized (AsyncTask.class) {
270             if (sHandler == null) {
271                 sHandler = new InternalHandler();
272             }
273             return sHandler;
274         }
275     }
276 
277     /** @hide */
setDefaultExecutor(Executor exec)278     public static void setDefaultExecutor(Executor exec) {
279         sDefaultExecutor = exec;
280     }
281 
282     /**
283      * Creates a new asynchronous task. This constructor must be invoked on the UI thread.
284      */
AsyncTask()285     public AsyncTask() {
286         mWorker = new WorkerRunnable<Params, Result>() {
287             public Result call() throws Exception {
288                 mTaskInvoked.set(true);
289 
290                 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
291                 //noinspection unchecked
292                 return postResult(doInBackground(mParams));
293             }
294         };
295 
296         mFuture = new FutureTask<Result>(mWorker) {
297             @Override
298             protected void done() {
299                 try {
300                     postResultIfNotInvoked(get());
301                 } catch (InterruptedException e) {
302                     android.util.Log.w(LOG_TAG, e);
303                 } catch (ExecutionException e) {
304                     throw new RuntimeException("An error occured while executing doInBackground()",
305                             e.getCause());
306                 } catch (CancellationException e) {
307                     postResultIfNotInvoked(null);
308                 }
309             }
310         };
311     }
312 
postResultIfNotInvoked(Result result)313     private void postResultIfNotInvoked(Result result) {
314         final boolean wasTaskInvoked = mTaskInvoked.get();
315         if (!wasTaskInvoked) {
316             postResult(result);
317         }
318     }
319 
postResult(Result result)320     private Result postResult(Result result) {
321         @SuppressWarnings("unchecked")
322         Message message = getHandler().obtainMessage(MESSAGE_POST_RESULT,
323                 new AsyncTaskResult<Result>(this, result));
324         message.sendToTarget();
325         return result;
326     }
327 
328     /**
329      * Returns the current status of this task.
330      *
331      * @return The current status.
332      */
getStatus()333     public final Status getStatus() {
334         return mStatus;
335     }
336 
337     /**
338      * Override this method to perform a computation on a background thread. The
339      * specified parameters are the parameters passed to {@link #execute}
340      * by the caller of this task.
341      *
342      * This method can call {@link #publishProgress} to publish updates
343      * on the UI thread.
344      *
345      * @param params The parameters of the task.
346      *
347      * @return A result, defined by the subclass of this task.
348      *
349      * @see #onPreExecute()
350      * @see #onPostExecute
351      * @see #publishProgress
352      */
doInBackground(Params... params)353     protected abstract Result doInBackground(Params... params);
354 
355     /**
356      * Runs on the UI thread before {@link #doInBackground}.
357      *
358      * @see #onPostExecute
359      * @see #doInBackground
360      */
onPreExecute()361     protected void onPreExecute() {
362     }
363 
364     /**
365      * <p>Runs on the UI thread after {@link #doInBackground}. The
366      * specified result is the value returned by {@link #doInBackground}.</p>
367      *
368      * <p>This method won't be invoked if the task was cancelled.</p>
369      *
370      * @param result The result of the operation computed by {@link #doInBackground}.
371      *
372      * @see #onPreExecute
373      * @see #doInBackground
374      * @see #onCancelled(Object)
375      */
376     @SuppressWarnings({"UnusedDeclaration"})
onPostExecute(Result result)377     protected void onPostExecute(Result result) {
378     }
379 
380     /**
381      * Runs on the UI thread after {@link #publishProgress} is invoked.
382      * The specified values are the values passed to {@link #publishProgress}.
383      *
384      * @param values The values indicating progress.
385      *
386      * @see #publishProgress
387      * @see #doInBackground
388      */
389     @SuppressWarnings({"UnusedDeclaration"})
onProgressUpdate(Progress... values)390     protected void onProgressUpdate(Progress... values) {
391     }
392 
393     /**
394      * <p>Runs on the UI thread after {@link #cancel(boolean)} is invoked and
395      * {@link #doInBackground(Object[])} has finished.</p>
396      *
397      * <p>The default implementation simply invokes {@link #onCancelled()} and
398      * ignores the result. If you write your own implementation, do not call
399      * <code>super.onCancelled(result)</code>.</p>
400      *
401      * @param result The result, if any, computed in
402      *               {@link #doInBackground(Object[])}, can be null
403      *
404      * @see #cancel(boolean)
405      * @see #isCancelled()
406      */
407     @SuppressWarnings({"UnusedParameters"})
onCancelled(Result result)408     protected void onCancelled(Result result) {
409         onCancelled();
410     }
411 
412     /**
413      * <p>Applications should preferably override {@link #onCancelled(Object)}.
414      * This method is invoked by the default implementation of
415      * {@link #onCancelled(Object)}.</p>
416      *
417      * <p>Runs on the UI thread after {@link #cancel(boolean)} is invoked and
418      * {@link #doInBackground(Object[])} has finished.</p>
419      *
420      * @see #onCancelled(Object)
421      * @see #cancel(boolean)
422      * @see #isCancelled()
423      */
onCancelled()424     protected void onCancelled() {
425     }
426 
427     /**
428      * Returns <tt>true</tt> if this task was cancelled before it completed
429      * normally. If you are calling {@link #cancel(boolean)} on the task,
430      * the value returned by this method should be checked periodically from
431      * {@link #doInBackground(Object[])} to end the task as soon as possible.
432      *
433      * @return <tt>true</tt> if task was cancelled before it completed
434      *
435      * @see #cancel(boolean)
436      */
isCancelled()437     public final boolean isCancelled() {
438         return mCancelled.get();
439     }
440 
441     /**
442      * <p>Attempts to cancel execution of this task.  This attempt will
443      * fail if the task has already completed, already been cancelled,
444      * or could not be cancelled for some other reason. If successful,
445      * and this task has not started when <tt>cancel</tt> is called,
446      * this task should never run. If the task has already started,
447      * then the <tt>mayInterruptIfRunning</tt> parameter determines
448      * whether the thread executing this task should be interrupted in
449      * an attempt to stop the task.</p>
450      *
451      * <p>Calling this method will result in {@link #onCancelled(Object)} being
452      * invoked on the UI thread after {@link #doInBackground(Object[])}
453      * returns. Calling this method guarantees that {@link #onPostExecute(Object)}
454      * is never invoked. After invoking this method, you should check the
455      * value returned by {@link #isCancelled()} periodically from
456      * {@link #doInBackground(Object[])} to finish the task as early as
457      * possible.</p>
458      *
459      * @param mayInterruptIfRunning <tt>true</tt> if the thread executing this
460      *        task should be interrupted; otherwise, in-progress tasks are allowed
461      *        to complete.
462      *
463      * @return <tt>false</tt> if the task could not be cancelled,
464      *         typically because it has already completed normally;
465      *         <tt>true</tt> otherwise
466      *
467      * @see #isCancelled()
468      * @see #onCancelled(Object)
469      */
cancel(boolean mayInterruptIfRunning)470     public final boolean cancel(boolean mayInterruptIfRunning) {
471         mCancelled.set(true);
472         return mFuture.cancel(mayInterruptIfRunning);
473     }
474 
475     /**
476      * Waits if necessary for the computation to complete, and then
477      * retrieves its result.
478      *
479      * @return The computed result.
480      *
481      * @throws CancellationException If the computation was cancelled.
482      * @throws ExecutionException If the computation threw an exception.
483      * @throws InterruptedException If the current thread was interrupted
484      *         while waiting.
485      */
get()486     public final Result get() throws InterruptedException, ExecutionException {
487         return mFuture.get();
488     }
489 
490     /**
491      * Waits if necessary for at most the given time for the computation
492      * to complete, and then retrieves its result.
493      *
494      * @param timeout Time to wait before cancelling the operation.
495      * @param unit The time unit for the timeout.
496      *
497      * @return The computed result.
498      *
499      * @throws CancellationException If the computation was cancelled.
500      * @throws ExecutionException If the computation threw an exception.
501      * @throws InterruptedException If the current thread was interrupted
502      *         while waiting.
503      * @throws TimeoutException If the wait timed out.
504      */
get(long timeout, TimeUnit unit)505     public final Result get(long timeout, TimeUnit unit) throws InterruptedException,
506             ExecutionException, TimeoutException {
507         return mFuture.get(timeout, unit);
508     }
509 
510     /**
511      * Executes the task with the specified parameters. The task returns
512      * itself (this) so that the caller can keep a reference to it.
513      *
514      * <p>Note: this function schedules the task on a queue for a single background
515      * thread or pool of threads depending on the platform version.  When first
516      * introduced, AsyncTasks were executed serially on a single background thread.
517      * Starting with {@link android.os.Build.VERSION_CODES#DONUT}, this was changed
518      * to a pool of threads allowing multiple tasks to operate in parallel. Starting
519      * {@link android.os.Build.VERSION_CODES#HONEYCOMB}, tasks are back to being
520      * executed on a single thread to avoid common application errors caused
521      * by parallel execution.  If you truly want parallel execution, you can use
522      * the {@link #executeOnExecutor} version of this method
523      * with {@link #THREAD_POOL_EXECUTOR}; however, see commentary there for warnings
524      * on its use.
525      *
526      * <p>This method must be invoked on the UI thread.
527      *
528      * @param params The parameters of the task.
529      *
530      * @return This instance of AsyncTask.
531      *
532      * @throws IllegalStateException If {@link #getStatus()} returns either
533      *         {@link AsyncTask.Status#RUNNING} or {@link AsyncTask.Status#FINISHED}.
534      *
535      * @see #executeOnExecutor(java.util.concurrent.Executor, Object[])
536      * @see #execute(Runnable)
537      */
execute(Params... params)538     public final AsyncTask<Params, Progress, Result> execute(Params... params) {
539         return executeOnExecutor(sDefaultExecutor, params);
540     }
541 
542     /**
543      * Executes the task with the specified parameters. The task returns
544      * itself (this) so that the caller can keep a reference to it.
545      *
546      * <p>This method is typically used with {@link #THREAD_POOL_EXECUTOR} to
547      * allow multiple tasks to run in parallel on a pool of threads managed by
548      * AsyncTask, however you can also use your own {@link Executor} for custom
549      * behavior.
550      *
551      * <p><em>Warning:</em> Allowing multiple tasks to run in parallel from
552      * a thread pool is generally <em>not</em> what one wants, because the order
553      * of their operation is not defined.  For example, if these tasks are used
554      * to modify any state in common (such as writing a file due to a button click),
555      * there are no guarantees on the order of the modifications.
556      * Without careful work it is possible in rare cases for the newer version
557      * of the data to be over-written by an older one, leading to obscure data
558      * loss and stability issues.  Such changes are best
559      * executed in serial; to guarantee such work is serialized regardless of
560      * platform version you can use this function with {@link #SERIAL_EXECUTOR}.
561      *
562      * <p>This method must be invoked on the UI thread.
563      *
564      * @param exec The executor to use.  {@link #THREAD_POOL_EXECUTOR} is available as a
565      *              convenient process-wide thread pool for tasks that are loosely coupled.
566      * @param params The parameters of the task.
567      *
568      * @return This instance of AsyncTask.
569      *
570      * @throws IllegalStateException If {@link #getStatus()} returns either
571      *         {@link AsyncTask.Status#RUNNING} or {@link AsyncTask.Status#FINISHED}.
572      *
573      * @see #execute(Object[])
574      */
executeOnExecutor(Executor exec, Params... params)575     public final AsyncTask<Params, Progress, Result> executeOnExecutor(Executor exec,
576             Params... params) {
577         if (mStatus != Status.PENDING) {
578             switch (mStatus) {
579                 case RUNNING:
580                     throw new IllegalStateException("Cannot execute task:"
581                             + " the task is already running.");
582                 case FINISHED:
583                     throw new IllegalStateException("Cannot execute task:"
584                             + " the task has already been executed "
585                             + "(a task can be executed only once)");
586             }
587         }
588 
589         mStatus = Status.RUNNING;
590 
591         onPreExecute();
592 
593         mWorker.mParams = params;
594         exec.execute(mFuture);
595 
596         return this;
597     }
598 
599     /**
600      * Convenience version of {@link #execute(Object...)} for use with
601      * a simple Runnable object. See {@link #execute(Object[])} for more
602      * information on the order of execution.
603      *
604      * @see #execute(Object[])
605      * @see #executeOnExecutor(java.util.concurrent.Executor, Object[])
606      */
execute(Runnable runnable)607     public static void execute(Runnable runnable) {
608         sDefaultExecutor.execute(runnable);
609     }
610 
611     /**
612      * This method can be invoked from {@link #doInBackground} to
613      * publish updates on the UI thread while the background computation is
614      * still running. Each call to this method will trigger the execution of
615      * {@link #onProgressUpdate} on the UI thread.
616      *
617      * {@link #onProgressUpdate} will not be called if the task has been
618      * canceled.
619      *
620      * @param values The progress values to update the UI with.
621      *
622      * @see #onProgressUpdate
623      * @see #doInBackground
624      */
publishProgress(Progress... values)625     protected final void publishProgress(Progress... values) {
626         if (!isCancelled()) {
627             getHandler().obtainMessage(MESSAGE_POST_PROGRESS,
628                     new AsyncTaskResult<Progress>(this, values)).sendToTarget();
629         }
630     }
631 
finish(Result result)632     private void finish(Result result) {
633         if (isCancelled()) {
634             onCancelled(result);
635         } else {
636             onPostExecute(result);
637         }
638         mStatus = Status.FINISHED;
639     }
640 
641     private static class InternalHandler extends Handler {
InternalHandler()642         public InternalHandler() {
643             super(Looper.getMainLooper());
644         }
645 
646         @SuppressWarnings({"unchecked", "RawUseOfParameterizedType"})
647         @Override
handleMessage(Message msg)648         public void handleMessage(Message msg) {
649             AsyncTaskResult<?> result = (AsyncTaskResult<?>) msg.obj;
650             switch (msg.what) {
651                 case MESSAGE_POST_RESULT:
652                     // There is only one result
653                     result.mTask.finish(result.mData[0]);
654                     break;
655                 case MESSAGE_POST_PROGRESS:
656                     result.mTask.onProgressUpdate(result.mData);
657                     break;
658             }
659         }
660     }
661 
662     private static abstract class WorkerRunnable<Params, Result> implements Callable<Result> {
663         Params[] mParams;
664     }
665 
666     @SuppressWarnings({"RawUseOfParameterizedType"})
667     private static class AsyncTaskResult<Data> {
668         final AsyncTask mTask;
669         final Data[] mData;
670 
AsyncTaskResult(AsyncTask task, Data... data)671         AsyncTaskResult(AsyncTask task, Data... data) {
672             mTask = task;
673             mData = data;
674         }
675     }
676 }
677