AsyncTask.java revision a2ea747faaf5fcd437afbaaf4085cfc29e7c16b8
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.concurrent.BlockingQueue;
20import java.util.concurrent.Callable;
21import java.util.concurrent.CancellationException;
22import java.util.concurrent.ExecutionException;
23import java.util.concurrent.FutureTask;
24import java.util.concurrent.LinkedBlockingQueue;
25import java.util.concurrent.ThreadFactory;
26import java.util.concurrent.ThreadPoolExecutor;
27import java.util.concurrent.TimeUnit;
28import java.util.concurrent.TimeoutException;
29import java.util.concurrent.atomic.AtomicInteger;
30
31/**
32 * <p>AsyncTask enables proper and easy use of the UI thread. This class allows to
33 * perform background operations and publish results on the UI thread without
34 * having to manipulate threads and/or handlers.</p>
35 *
36 * <p>An asynchronous task is defined by a computation that runs on a background thread and
37 * whose result is published on the UI thread. An asynchronous task is defined by 3 generic
38 * types, called <code>Params</code>, <code>Progress</code> and <code>Result</code>,
39 * and 4 steps, called <code>onPreExecute</code>, <code>doInBackground</code>,
40 * <code>onProgressUpdate</code> and <code>onPostExecute</code>.</p>
41 *
42 * <h2>Usage</h2>
43 * <p>AsyncTask must be subclassed to be used. The subclass will override at least
44 * one method ({@link #doInBackground}), and most often will override a
45 * second one ({@link #onPostExecute}.)</p>
46 *
47 * <p>Here is an example of subclassing:</p>
48 * <pre class="prettyprint">
49 * private class DownloadFilesTask extends AsyncTask&lt;URL, Integer, Long&gt; {
50 *     protected Long doInBackground(URL... urls) {
51 *         int count = urls.length;
52 *         long totalSize = 0;
53 *         for (int i = 0; i < count; i++) {
54 *             totalSize += Downloader.downloadFile(urls[i]);
55 *             publishProgress((int) ((i / (float) count) * 100));
56 *         }
57 *         return totalSize;
58 *     }
59 *
60 *     protected void onProgressUpdate(Integer... progress) {
61 *         setProgressPercent(progress[0]);
62 *     }
63 *
64 *     protected void onPostExecute(Long result) {
65 *         showDialog("Downloaded " + result + " bytes");
66 *     }
67 * }
68 * </pre>
69 *
70 * <p>Once created, a task is executed very simply:</p>
71 * <pre class="prettyprint">
72 * new DownloadFilesTask().execute(url1, url2, url3);
73 * </pre>
74 *
75 * <h2>AsyncTask's generic types</h2>
76 * <p>The three types used by an asynchronous task are the following:</p>
77 * <ol>
78 *     <li><code>Params</code>, the type of the parameters sent to the task upon
79 *     execution.</li>
80 *     <li><code>Progress</code>, the type of the progress units published during
81 *     the background computation.</li>
82 *     <li><code>Result</code>, the type of the result of the background
83 *     computation.</li>
84 * </ol>
85 * <p>Not all types are always used by an asynchronous task. To mark a type as unused,
86 * simply use the type {@link Void}:</p>
87 * <pre>
88 * private class MyTask extends AsyncTask&lt;Void, Void, Void&gt; { ... }
89 * </pre>
90 *
91 * <h2>The 4 steps</h2>
92 * <p>When an asynchronous task is executed, the task goes through 4 steps:</p>
93 * <ol>
94 *     <li>{@link #onPreExecute()}, invoked on the UI thread immediately after the task
95 *     is executed. This step is normally used to setup the task, for instance by
96 *     showing a progress bar in the user interface.</li>
97 *     <li>{@link #doInBackground}, invoked on the background thread
98 *     immediately after {@link #onPreExecute()} finishes executing. This step is used
99 *     to perform background computation that can take a long time. The parameters
100 *     of the asynchronous task are passed to this step. The result of the computation must
101 *     be returned by this step and will be passed back to the last step. This step
102 *     can also use {@link #publishProgress} to publish one or more units
103 *     of progress. These values are published on the UI thread, in the
104 *     {@link #onProgressUpdate} step.</li>
105 *     <li>{@link #onProgressUpdate}, invoked on the UI thread after a
106 *     call to {@link #publishProgress}. The timing of the execution is
107 *     undefined. This method is used to display any form of progress in the user
108 *     interface while the background computation is still executing. For instance,
109 *     it can be used to animate a progress bar or show logs in a text field.</li>
110 *     <li>{@link #onPostExecute}, invoked on the UI thread after the background
111 *     computation finishes. The result of the background computation is passed to
112 *     this step as a parameter.</li>
113 * </ol>
114 *
115 * <h2>Threading rules</h2>
116 * <p>There are a few threading rules that must be followed for this class to
117 * work properly:</p>
118 * <ul>
119 *     <li>The task instance must be created on the UI thread.</li>
120 *     <li>{@link #execute} must be invoked on the UI thread.</li>
121 *     <li>Do not call {@link #onPreExecute()}, {@link #onPostExecute},
122 *     {@link #doInBackground}, {@link #onProgressUpdate} manually.</li>
123 *     <li>The task can be executed only once (an exception will be thrown if
124 *     a second execution is attempted.)</li>
125 * </ul>
126 *
127 * <h2>Memory observability</h2>
128 * <p>AsyncTask guarantees that all callback calls are synchronized in such a way that the following
129 * operations are safe without explicit synchronizations.</p>
130 * <ul>
131 *     <li>Set member fields in the constructor or {@link #onPreExecute}, and refer to them
132 *     in {@link #doInBackground}.
133 *     <li>Set member fields in {@link #doInBackground}, and refer to them in
134 *     {@link #onProgressUpdate} and {@link #onPostExecute}.
135 * </ul>
136 */
137public abstract class AsyncTask<Params, Progress, Result> {
138    private static final String LOG_TAG = "AsyncTask";
139
140    private static final int CORE_POOL_SIZE = 5;
141    private static final int MAXIMUM_POOL_SIZE = 128;
142    private static final int KEEP_ALIVE = 1;
143
144    private static final BlockingQueue<Runnable> sWorkQueue =
145            new LinkedBlockingQueue<Runnable>(10);
146
147    private static final ThreadFactory sThreadFactory = new ThreadFactory() {
148        private final AtomicInteger mCount = new AtomicInteger(1);
149
150        public Thread newThread(Runnable r) {
151            return new Thread(r, "AsyncTask #" + mCount.getAndIncrement());
152        }
153    };
154
155    private static final ThreadPoolExecutor sExecutor = new ThreadPoolExecutor(CORE_POOL_SIZE,
156            MAXIMUM_POOL_SIZE, KEEP_ALIVE, TimeUnit.SECONDS, sWorkQueue, sThreadFactory);
157
158    private static final int MESSAGE_POST_RESULT = 0x1;
159    private static final int MESSAGE_POST_PROGRESS = 0x2;
160    private static final int MESSAGE_POST_CANCEL = 0x3;
161
162    private static final InternalHandler sHandler = new InternalHandler();
163
164    private final WorkerRunnable<Params, Result> mWorker;
165    private final FutureTask<Result> mFuture;
166
167    private volatile Status mStatus = Status.PENDING;
168
169    /**
170     * Indicates the current status of the task. Each status will be set only once
171     * during the lifetime of a task.
172     */
173    public enum Status {
174        /**
175         * Indicates that the task has not been executed yet.
176         */
177        PENDING,
178        /**
179         * Indicates that the task is running.
180         */
181        RUNNING,
182        /**
183         * Indicates that {@link AsyncTask#onPostExecute} has finished.
184         */
185        FINISHED,
186    }
187
188    /** @hide Used to force static handler to be created. */
189    public static void init() {
190        sHandler.getLooper();
191    }
192
193    /**
194     * Creates a new asynchronous task. This constructor must be invoked on the UI thread.
195     */
196    public AsyncTask() {
197        mWorker = new WorkerRunnable<Params, Result>() {
198            public Result call() throws Exception {
199                Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
200                return doInBackground(mParams);
201            }
202        };
203
204        mFuture = new FutureTask<Result>(mWorker) {
205
206            @Override
207            protected void set(Result v) {
208                super.set(v);
209                if (isCancelled()) {
210                    Message message = sHandler.obtainMessage(MESSAGE_POST_CANCEL,
211                            new AsyncTaskResult<Result>(AsyncTask.this, (Result[]) null));
212                    message.sendToTarget();
213                }
214            }
215
216            @Override
217            protected void done() {
218                Message message;
219                Result result = null;
220
221                try {
222                    result = get();
223                } catch (InterruptedException e) {
224                    android.util.Log.w(LOG_TAG, e);
225                } catch (ExecutionException e) {
226                    throw new RuntimeException("An error occured while executing doInBackground()",
227                            e.getCause());
228                } catch (CancellationException e) {
229                    message = sHandler.obtainMessage(MESSAGE_POST_CANCEL,
230                            new AsyncTaskResult<Result>(AsyncTask.this, (Result[]) null));
231                    message.sendToTarget();
232                    return;
233                } catch (Throwable t) {
234                    throw new RuntimeException("An error occured while executing "
235                            + "doInBackground()", t);
236                }
237
238                message = sHandler.obtainMessage(MESSAGE_POST_RESULT,
239                        new AsyncTaskResult<Result>(AsyncTask.this, result));
240                message.sendToTarget();
241            }
242        };
243    }
244
245    /**
246     * Returns the current status of this task.
247     *
248     * @return The current status.
249     */
250    public final Status getStatus() {
251        return mStatus;
252    }
253
254    /**
255     * Override this method to perform a computation on a background thread. The
256     * specified parameters are the parameters passed to {@link #execute}
257     * by the caller of this task.
258     *
259     * This method can call {@link #publishProgress} to publish updates
260     * on the UI thread.
261     *
262     * @param params The parameters of the task.
263     *
264     * @return A result, defined by the subclass of this task.
265     *
266     * @see #onPreExecute()
267     * @see #onPostExecute
268     * @see #publishProgress
269     */
270    protected abstract Result doInBackground(Params... params);
271
272    /**
273     * Runs on the UI thread before {@link #doInBackground}.
274     *
275     * @see #onPostExecute
276     * @see #doInBackground
277     */
278    protected void onPreExecute() {
279    }
280
281    /**
282     * Runs on the UI thread after {@link #doInBackground}. The
283     * specified result is the value returned by {@link #doInBackground}
284     * or null if the task was cancelled or an exception occurred.
285     *
286     * @param result The result of the operation computed by {@link #doInBackground}.
287     *
288     * @see #onPreExecute
289     * @see #doInBackground
290     */
291    @SuppressWarnings({"UnusedDeclaration"})
292    protected void onPostExecute(Result result) {
293    }
294
295    /**
296     * Runs on the UI thread after {@link #publishProgress} is invoked.
297     * The specified values are the values passed to {@link #publishProgress}.
298     *
299     * @param values The values indicating progress.
300     *
301     * @see #publishProgress
302     * @see #doInBackground
303     */
304    @SuppressWarnings({"UnusedDeclaration"})
305    protected void onProgressUpdate(Progress... values) {
306    }
307
308    /**
309     * Runs on the UI thread after {@link #cancel(boolean)} is invoked.
310     *
311     * @see #cancel(boolean)
312     * @see #isCancelled()
313     */
314    protected void onCancelled() {
315    }
316
317    /**
318     * Returns <tt>true</tt> if this task was cancelled before it completed
319     * normally.
320     *
321     * @return <tt>true</tt> if task was cancelled before it completed
322     *
323     * @see #cancel(boolean)
324     */
325    public final boolean isCancelled() {
326        return mFuture.isCancelled();
327    }
328
329    /**
330     * Attempts to cancel execution of this task.  This attempt will
331     * fail if the task has already completed, already been cancelled,
332     * or could not be cancelled for some other reason. If successful,
333     * and this task has not started when <tt>cancel</tt> is called,
334     * this task should never run.  If the task has already started,
335     * then the <tt>mayInterruptIfRunning</tt> parameter determines
336     * whether the thread executing this task should be interrupted in
337     * an attempt to stop the task.
338     *
339     * @param mayInterruptIfRunning <tt>true</tt> if the thread executing this
340     *        task should be interrupted; otherwise, in-progress tasks are allowed
341     *        to complete.
342     *
343     * @return <tt>false</tt> if the task could not be cancelled,
344     *         typically because it has already completed normally;
345     *         <tt>true</tt> otherwise
346     *
347     * @see #isCancelled()
348     * @see #onCancelled()
349     */
350    public final boolean cancel(boolean mayInterruptIfRunning) {
351        return mFuture.cancel(mayInterruptIfRunning);
352    }
353
354    /**
355     * Waits if necessary for the computation to complete, and then
356     * retrieves its result.
357     *
358     * @return The computed result.
359     *
360     * @throws CancellationException If the computation was cancelled.
361     * @throws ExecutionException If the computation threw an exception.
362     * @throws InterruptedException If the current thread was interrupted
363     *         while waiting.
364     */
365    public final Result get() throws InterruptedException, ExecutionException {
366        return mFuture.get();
367    }
368
369    /**
370     * Waits if necessary for at most the given time for the computation
371     * to complete, and then retrieves its result.
372     *
373     * @param timeout Time to wait before cancelling the operation.
374     * @param unit The time unit for the timeout.
375     *
376     * @return The computed result.
377     *
378     * @throws CancellationException If the computation was cancelled.
379     * @throws ExecutionException If the computation threw an exception.
380     * @throws InterruptedException If the current thread was interrupted
381     *         while waiting.
382     * @throws TimeoutException If the wait timed out.
383     */
384    public final Result get(long timeout, TimeUnit unit) throws InterruptedException,
385            ExecutionException, TimeoutException {
386        return mFuture.get(timeout, unit);
387    }
388
389    /**
390     * Executes the task with the specified parameters. The task returns
391     * itself (this) so that the caller can keep a reference to it.
392     *
393     * This method must be invoked on the UI thread.
394     *
395     * @param params The parameters of the task.
396     *
397     * @return This instance of AsyncTask.
398     *
399     * @throws IllegalStateException If {@link #getStatus()} returns either
400     *         {@link AsyncTask.Status#RUNNING} or {@link AsyncTask.Status#FINISHED}.
401     */
402    public final AsyncTask<Params, Progress, Result> execute(Params... params) {
403        if (mStatus != Status.PENDING) {
404            switch (mStatus) {
405                case RUNNING:
406                    throw new IllegalStateException("Cannot execute task:"
407                            + " the task is already running.");
408                case FINISHED:
409                    throw new IllegalStateException("Cannot execute task:"
410                            + " the task has already been executed "
411                            + "(a task can be executed only once)");
412            }
413        }
414
415        mStatus = Status.RUNNING;
416
417        onPreExecute();
418
419        mWorker.mParams = params;
420        sExecutor.execute(mFuture);
421
422        return this;
423    }
424
425    /**
426     * This method can be invoked from {@link #doInBackground} to
427     * publish updates on the UI thread while the background computation is
428     * still running. Each call to this method will trigger the execution of
429     * {@link #onProgressUpdate} on the UI thread.
430     *
431     * {@link #onProgressUpdate} will note be called if the task has been
432     * canceled.
433     *
434     * @param values The progress values to update the UI with.
435     *
436     * @see #onProgressUpdate
437     * @see #doInBackground
438     */
439    protected final void publishProgress(Progress... values) {
440        if (!isCancelled()) {
441            sHandler.obtainMessage(MESSAGE_POST_PROGRESS,
442                    new AsyncTaskResult<Progress>(this, values)).sendToTarget();
443        }
444    }
445
446    private void finish(Result result) {
447        if (isCancelled()) result = null;
448        onPostExecute(result);
449        mStatus = Status.FINISHED;
450    }
451
452    private static class InternalHandler extends Handler {
453        @SuppressWarnings({"unchecked", "RawUseOfParameterizedType"})
454        @Override
455        public void handleMessage(Message msg) {
456            AsyncTaskResult result = (AsyncTaskResult) msg.obj;
457            switch (msg.what) {
458                case MESSAGE_POST_RESULT:
459                    // There is only one result
460                    result.mTask.finish(result.mData[0]);
461                    break;
462                case MESSAGE_POST_PROGRESS:
463                    result.mTask.onProgressUpdate(result.mData);
464                    break;
465                case MESSAGE_POST_CANCEL:
466                    result.mTask.onCancelled();
467                    break;
468            }
469        }
470    }
471
472    private static abstract class WorkerRunnable<Params, Result> implements Callable<Result> {
473        Params[] mParams;
474    }
475
476    @SuppressWarnings({"RawUseOfParameterizedType"})
477    private static class AsyncTaskResult<Data> {
478        final AsyncTask mTask;
479        final Data[] mData;
480
481        AsyncTaskResult(AsyncTask task, Data... data) {
482            mTask = task;
483            mData = data;
484        }
485    }
486}
487