AsyncTask.java revision b1ec5ef460ac62fa8d3e621794787336e513a8ef
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 AsyncTask class must be loaded on the UI thread. This is done
139 *     automatically as of {@link android.os.Build.VERSION_CODES#JELLY_BEAN}.</li>
140 *     <li>The task instance must be created on the UI thread.</li>
141 *     <li>{@link #execute} must be invoked on the UI thread.</li>
142 *     <li>Do not call {@link #onPreExecute()}, {@link #onPostExecute},
143 *     {@link #doInBackground}, {@link #onProgressUpdate} manually.</li>
144 *     <li>The task can be executed only once (an exception will be thrown if
145 *     a second execution is attempted.)</li>
146 * </ul>
147 *
148 * <h2>Memory observability</h2>
149 * <p>AsyncTask guarantees that all callback calls are synchronized in such a way that the following
150 * operations are safe without explicit synchronizations.</p>
151 * <ul>
152 *     <li>Set member fields in the constructor or {@link #onPreExecute}, and refer to them
153 *     in {@link #doInBackground}.
154 *     <li>Set member fields in {@link #doInBackground}, and refer to them in
155 *     {@link #onProgressUpdate} and {@link #onPostExecute}.
156 * </ul>
157 */
158public abstract class AsyncTask<Params, Progress, Result> {
159    private static final String LOG_TAG = "AsyncTask";
160
161    private static final int CORE_POOL_SIZE = 5;
162    private static final int MAXIMUM_POOL_SIZE = 128;
163    private static final int KEEP_ALIVE = 1;
164
165    private static final ThreadFactory sThreadFactory = new ThreadFactory() {
166        private final AtomicInteger mCount = new AtomicInteger(1);
167
168        public Thread newThread(Runnable r) {
169            return new Thread(r, "AsyncTask #" + mCount.getAndIncrement());
170        }
171    };
172
173    private static final BlockingQueue<Runnable> sPoolWorkQueue =
174            new LinkedBlockingQueue<Runnable>(10);
175
176    /**
177     * An {@link Executor} that can be used to execute tasks in parallel.
178     */
179    public static final Executor THREAD_POOL_EXECUTOR
180            = new ThreadPoolExecutor(CORE_POOL_SIZE, MAXIMUM_POOL_SIZE, KEEP_ALIVE,
181                    TimeUnit.SECONDS, sPoolWorkQueue, sThreadFactory);
182
183    /**
184     * An {@link Executor} that executes tasks one at a time in serial
185     * order.  This serialization is global to a particular process.
186     */
187    public static final Executor SERIAL_EXECUTOR = new SerialExecutor();
188
189    private static final int MESSAGE_POST_RESULT = 0x1;
190    private static final int MESSAGE_POST_PROGRESS = 0x2;
191
192    private static final InternalHandler sHandler = new InternalHandler();
193
194    private static volatile Executor sDefaultExecutor = SERIAL_EXECUTOR;
195    private final WorkerRunnable<Params, Result> mWorker;
196    private final FutureTask<Result> mFuture;
197
198    private volatile Status mStatus = Status.PENDING;
199
200    private final AtomicBoolean mCancelled = new AtomicBoolean();
201    private final AtomicBoolean mTaskInvoked = new AtomicBoolean();
202
203    private static class SerialExecutor implements Executor {
204        final ArrayDeque<Runnable> mTasks = new ArrayDeque<Runnable>();
205        Runnable mActive;
206
207        public synchronized void execute(final Runnable r) {
208            mTasks.offer(new Runnable() {
209                public void run() {
210                    try {
211                        r.run();
212                    } finally {
213                        scheduleNext();
214                    }
215                }
216            });
217            if (mActive == null) {
218                scheduleNext();
219            }
220        }
221
222        protected synchronized void scheduleNext() {
223            if ((mActive = mTasks.poll()) != null) {
224                THREAD_POOL_EXECUTOR.execute(mActive);
225            }
226        }
227    }
228
229    /**
230     * Indicates the current status of the task. Each status will be set only once
231     * during the lifetime of a task.
232     */
233    public enum Status {
234        /**
235         * Indicates that the task has not been executed yet.
236         */
237        PENDING,
238        /**
239         * Indicates that the task is running.
240         */
241        RUNNING,
242        /**
243         * Indicates that {@link AsyncTask#onPostExecute} has finished.
244         */
245        FINISHED,
246    }
247
248    /** @hide Used to force static handler to be created. */
249    public static void init() {
250        sHandler.getLooper();
251    }
252
253    /** @hide */
254    public static void setDefaultExecutor(Executor exec) {
255        sDefaultExecutor = exec;
256    }
257
258    /**
259     * Creates a new asynchronous task. This constructor must be invoked on the UI thread.
260     */
261    public AsyncTask() {
262        mWorker = new WorkerRunnable<Params, Result>() {
263            public Result call() throws Exception {
264                mTaskInvoked.set(true);
265
266                Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
267                //noinspection unchecked
268                return postResult(doInBackground(mParams));
269            }
270        };
271
272        mFuture = new FutureTask<Result>(mWorker) {
273            @Override
274            protected void done() {
275                try {
276                    postResultIfNotInvoked(get());
277                } catch (InterruptedException e) {
278                    android.util.Log.w(LOG_TAG, e);
279                } catch (ExecutionException e) {
280                    throw new RuntimeException("An error occured while executing doInBackground()",
281                            e.getCause());
282                } catch (CancellationException e) {
283                    postResultIfNotInvoked(null);
284                }
285            }
286        };
287    }
288
289    private void postResultIfNotInvoked(Result result) {
290        final boolean wasTaskInvoked = mTaskInvoked.get();
291        if (!wasTaskInvoked) {
292            postResult(result);
293        }
294    }
295
296    private Result postResult(Result result) {
297        @SuppressWarnings("unchecked")
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 mCancelled.get();
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        mCancelled.set(true);
448        return mFuture.cancel(mayInterruptIfRunning);
449    }
450
451    /**
452     * Waits if necessary for the computation to complete, and then
453     * retrieves its result.
454     *
455     * @return The computed result.
456     *
457     * @throws CancellationException If the computation was cancelled.
458     * @throws ExecutionException If the computation threw an exception.
459     * @throws InterruptedException If the current thread was interrupted
460     *         while waiting.
461     */
462    public final Result get() throws InterruptedException, ExecutionException {
463        return mFuture.get();
464    }
465
466    /**
467     * Waits if necessary for at most the given time for the computation
468     * to complete, and then retrieves its result.
469     *
470     * @param timeout Time to wait before cancelling the operation.
471     * @param unit The time unit for the timeout.
472     *
473     * @return The computed result.
474     *
475     * @throws CancellationException If the computation was cancelled.
476     * @throws ExecutionException If the computation threw an exception.
477     * @throws InterruptedException If the current thread was interrupted
478     *         while waiting.
479     * @throws TimeoutException If the wait timed out.
480     */
481    public final Result get(long timeout, TimeUnit unit) throws InterruptedException,
482            ExecutionException, TimeoutException {
483        return mFuture.get(timeout, unit);
484    }
485
486    /**
487     * Executes the task with the specified parameters. The task returns
488     * itself (this) so that the caller can keep a reference to it.
489     *
490     * <p>Note: this function schedules the task on a queue for a single background
491     * thread or pool of threads depending on the platform version.  When first
492     * introduced, AsyncTasks were executed serially on a single background thread.
493     * Starting with {@link android.os.Build.VERSION_CODES#DONUT}, this was changed
494     * to a pool of threads allowing multiple tasks to operate in parallel.  After
495     * {@link android.os.Build.VERSION_CODES#HONEYCOMB}, it is planned to change this
496     * back to a single thread to avoid common application errors caused
497     * by parallel execution.  If you truly want parallel execution, you can use
498     * the {@link #executeOnExecutor} version of this method
499     * with {@link #THREAD_POOL_EXECUTOR}; however, see commentary there for warnings on
500     * its use.
501     *
502     * <p>This method must be invoked on the UI thread.
503     *
504     * @param params The parameters of the task.
505     *
506     * @return This instance of AsyncTask.
507     *
508     * @throws IllegalStateException If {@link #getStatus()} returns either
509     *         {@link AsyncTask.Status#RUNNING} or {@link AsyncTask.Status#FINISHED}.
510     */
511    public final AsyncTask<Params, Progress, Result> execute(Params... params) {
512        return executeOnExecutor(sDefaultExecutor, params);
513    }
514
515    /**
516     * Executes the task with the specified parameters. The task returns
517     * itself (this) so that the caller can keep a reference to it.
518     *
519     * <p>This method is typically used with {@link #THREAD_POOL_EXECUTOR} to
520     * allow multiple tasks to run in parallel on a pool of threads managed by
521     * AsyncTask, however you can also use your own {@link Executor} for custom
522     * behavior.
523     *
524     * <p><em>Warning:</em> Allowing multiple tasks to run in parallel from
525     * a thread pool is generally <em>not</em> what one wants, because the order
526     * of their operation is not defined.  For example, if these tasks are used
527     * to modify any state in common (such as writing a file due to a button click),
528     * there are no guarantees on the order of the modifications.
529     * Without careful work it is possible in rare cases for the newer version
530     * of the data to be over-written by an older one, leading to obscure data
531     * loss and stability issues.  Such changes are best
532     * executed in serial; to guarantee such work is serialized regardless of
533     * platform version you can use this function with {@link #SERIAL_EXECUTOR}.
534     *
535     * <p>This method must be invoked on the UI thread.
536     *
537     * @param exec The executor to use.  {@link #THREAD_POOL_EXECUTOR} is available as a
538     *              convenient process-wide thread pool for tasks that are loosely coupled.
539     * @param params The parameters of the task.
540     *
541     * @return This instance of AsyncTask.
542     *
543     * @throws IllegalStateException If {@link #getStatus()} returns either
544     *         {@link AsyncTask.Status#RUNNING} or {@link AsyncTask.Status#FINISHED}.
545     */
546    public final AsyncTask<Params, Progress, Result> executeOnExecutor(Executor exec,
547            Params... params) {
548        if (mStatus != Status.PENDING) {
549            switch (mStatus) {
550                case RUNNING:
551                    throw new IllegalStateException("Cannot execute task:"
552                            + " the task is already running.");
553                case FINISHED:
554                    throw new IllegalStateException("Cannot execute task:"
555                            + " the task has already been executed "
556                            + "(a task can be executed only once)");
557            }
558        }
559
560        mStatus = Status.RUNNING;
561
562        onPreExecute();
563
564        mWorker.mParams = params;
565        exec.execute(mFuture);
566
567        return this;
568    }
569
570    /**
571     * Convenience version of {@link #execute(Object...)} for use with
572     * a simple Runnable object.
573     */
574    public static void execute(Runnable runnable) {
575        sDefaultExecutor.execute(runnable);
576    }
577
578    /**
579     * This method can be invoked from {@link #doInBackground} to
580     * publish updates on the UI thread while the background computation is
581     * still running. Each call to this method will trigger the execution of
582     * {@link #onProgressUpdate} on the UI thread.
583     *
584     * {@link #onProgressUpdate} will note be called if the task has been
585     * canceled.
586     *
587     * @param values The progress values to update the UI with.
588     *
589     * @see #onProgressUpdate
590     * @see #doInBackground
591     */
592    protected final void publishProgress(Progress... values) {
593        if (!isCancelled()) {
594            sHandler.obtainMessage(MESSAGE_POST_PROGRESS,
595                    new AsyncTaskResult<Progress>(this, values)).sendToTarget();
596        }
597    }
598
599    private void finish(Result result) {
600        if (isCancelled()) {
601            onCancelled(result);
602        } else {
603            onPostExecute(result);
604        }
605        mStatus = Status.FINISHED;
606    }
607
608    private static class InternalHandler extends Handler {
609        @SuppressWarnings({"unchecked", "RawUseOfParameterizedType"})
610        @Override
611        public void handleMessage(Message msg) {
612            AsyncTaskResult result = (AsyncTaskResult) msg.obj;
613            switch (msg.what) {
614                case MESSAGE_POST_RESULT:
615                    // There is only one result
616                    result.mTask.finish(result.mData[0]);
617                    break;
618                case MESSAGE_POST_PROGRESS:
619                    result.mTask.onProgressUpdate(result.mData);
620                    break;
621            }
622        }
623    }
624
625    private static abstract class WorkerRunnable<Params, Result> implements Callable<Result> {
626        Params[] mParams;
627    }
628
629    @SuppressWarnings({"RawUseOfParameterizedType"})
630    private static class AsyncTaskResult<Data> {
631        final AsyncTask mTask;
632        final Data[] mData;
633
634        AsyncTaskResult(AsyncTask task, Data... data) {
635            mTask = task;
636            mData = data;
637        }
638    }
639}
640