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