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