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