blob: 1803604a85ee299d1fd99742e0ff6fa37e272c57 [file] [log] [blame]
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001/*
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
Joe Onorato81de61b2011-01-16 13:04:51 -080019import java.util.ArrayDeque;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080020import java.util.concurrent.BlockingQueue;
Gilles Debunne7f4b6842010-04-27 17:54:21 -070021import java.util.concurrent.Callable;
22import java.util.concurrent.CancellationException;
Joe Onorato81de61b2011-01-16 13:04:51 -080023import java.util.concurrent.Executor;
Gilles Debunne7f4b6842010-04-27 17:54:21 -070024import java.util.concurrent.ExecutionException;
25import java.util.concurrent.FutureTask;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080026import java.util.concurrent.LinkedBlockingQueue;
27import java.util.concurrent.ThreadFactory;
Gilles Debunne7f4b6842010-04-27 17:54:21 -070028import java.util.concurrent.ThreadPoolExecutor;
29import java.util.concurrent.TimeUnit;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080030import java.util.concurrent.TimeoutException;
Romain Guy5ba812b2011-01-10 13:33:12 -080031import java.util.concurrent.atomic.AtomicBoolean;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080032import 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>,
Gilles Debunne7f4b6842010-04-27 17:54:21 -070042 * and 4 steps, called <code>onPreExecute</code>, <code>doInBackground</code>,
43 * <code>onProgressUpdate</code> and <code>onPostExecute</code>.</p>
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080044 *
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>
Owen Lin202f5602009-12-28 15:54:23 +080088 * <p>Not all types are always used by an asynchronous task. To mark a type as unused,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080089 * simply use the type {@link Void}:</p>
90 * <pre>
Romain Guy6a1ae642009-05-02 22:52:17 -070091 * private class MyTask extends AsyncTask&lt;Void, Void, Void&gt; { ... }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080092 * </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>
Romain Guye95003e2011-01-09 13:53:06 -0800117 *
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.
Romain Guy5ba812b2011-01-10 13:33:12 -0800121 * 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>
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800126 *
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>
Makoto Onukiaa60a022010-08-31 09:42:12 -0700138 *
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>
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800148 */
149public abstract class AsyncTask<Params, Progress, Result> {
150 private static final String LOG_TAG = "AsyncTask";
151
Romain Guya9be47c2009-06-26 10:34:20 -0700152 private static final int CORE_POOL_SIZE = 5;
153 private static final int MAXIMUM_POOL_SIZE = 128;
Romain Guy6b424f42010-09-14 11:30:27 -0700154 private static final int KEEP_ALIVE = 1;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800155
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800156
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
Joe Onorato81de61b2011-01-16 13:04:51 -0800165 private static final BlockingQueue<Runnable> sPoolWorkQueue =
166 new LinkedBlockingQueue<Runnable>(10);
167
168 /**
Dianne Hackborn96438cd2011-01-25 21:42:37 -0800169 * An {@link Executor} that can be used to execute tasks in parallel.
Joe Onorato81de61b2011-01-16 13:04:51 -0800170 */
Dianne Hackborn96438cd2011-01-25 21:42:37 -0800171 public static final Executor THREAD_POOL_EXECUTOR
Joe Onorato81de61b2011-01-16 13:04:51 -0800172 = new ThreadPoolExecutor(CORE_POOL_SIZE, MAXIMUM_POOL_SIZE, KEEP_ALIVE,
173 TimeUnit.SECONDS, sPoolWorkQueue, sThreadFactory);
174
Dianne Hackborn96438cd2011-01-25 21:42:37 -0800175 /**
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();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800180
181 private static final int MESSAGE_POST_RESULT = 0x1;
182 private static final int MESSAGE_POST_PROGRESS = 0x2;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800183
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;
Romain Guy5ba812b2011-01-10 13:33:12 -0800190
191 private final AtomicBoolean mTaskInvoked = new AtomicBoolean();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800192
Joe Onorato81de61b2011-01-16 13:04:51 -0800193 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
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800219 /**
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
Dianne Hackborn23fdaf62010-08-06 12:16:55 -0700238 /** @hide Used to force static handler to be created. */
239 public static void init() {
240 sHandler.getLooper();
241 }
242
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800243 /**
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 {
Romain Guy5ba812b2011-01-10 13:33:12 -0800249 mTaskInvoked.set(true);
250
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800251 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
Romain Guy5ba812b2011-01-10 13:33:12 -0800252 return postResult(doInBackground(mParams));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800253 }
254 };
255
256 mFuture = new FutureTask<Result>(mWorker) {
257 @Override
258 protected void done() {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800259 try {
Romain Guy5ba812b2011-01-10 13:33:12 -0800260 final Result result = get();
261
262 postResultIfNotInvoked(result);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800263 } 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) {
Romain Guy5ba812b2011-01-10 13:33:12 -0800269 postResultIfNotInvoked(null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800270 } catch (Throwable t) {
271 throw new RuntimeException("An error occured while executing "
272 + "doInBackground()", t);
273 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800274 }
275 };
276 }
277
Romain Guy5ba812b2011-01-10 13:33:12 -0800278 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
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800292 /**
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 /**
Romain Guye95003e2011-01-09 13:53:06 -0800329 * <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>
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800333 *
334 * @param result The result of the operation computed by {@link #doInBackground}.
335 *
336 * @see #onPreExecute
337 * @see #doInBackground
Romain Guy5ba812b2011-01-10 13:33:12 -0800338 * @see #onCancelled(Object)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800339 */
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 /**
Romain Guy5ba812b2011-01-10 13:33:12 -0800358 * <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>
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800364 *
Romain Guy5ba812b2011-01-10 13:33:12 -0800365 * @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)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800385 * @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
Romain Guye95003e2011-01-09 13:53:06 -0800393 * 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.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800396 *
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 /**
Romain Guye95003e2011-01-09 13:53:06 -0800406 * <p>Attempts to cancel execution of this task. This attempt will
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800407 * 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,
Romain Guye95003e2011-01-09 13:53:06 -0800410 * this task should never run. If the task has already started,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800411 * then the <tt>mayInterruptIfRunning</tt> parameter determines
412 * whether the thread executing this task should be interrupted in
Romain Guye95003e2011-01-09 13:53:06 -0800413 * an attempt to stop the task.</p>
414 *
Romain Guy5ba812b2011-01-10 13:33:12 -0800415 * <p>Calling this method will result in {@link #onCancelled(Object)} being
Romain Guye95003e2011-01-09 13:53:06 -0800416 * 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>
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800422 *
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()
Romain Guy5ba812b2011-01-10 13:33:12 -0800432 * @see #onCancelled(Object)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800433 */
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
Dianne Hackborn96438cd2011-01-25 21:42:37 -0800475 * 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.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800488 *
Dianne Hackborn96438cd2011-01-25 21:42:37 -0800489 * <p>This method must be invoked on the UI thread.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800490 *
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) {
Dianne Hackborn96438cd2011-01-25 21:42:37 -0800499 return executeOnExecutor(THREAD_POOL_EXECUTOR, params);
Joe Onorato81de61b2011-01-16 13:04:51 -0800500 }
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.
Dianne Hackborn96438cd2011-01-25 21:42:37 -0800505 *
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}.
Joe Onorato81de61b2011-01-16 13:04:51 -0800521 *
Dianne Hackborn96438cd2011-01-25 21:42:37 -0800522 * <p>This method must be invoked on the UI thread.
Joe Onorato81de61b2011-01-16 13:04:51 -0800523 *
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) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800535 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;
Joe Onorato81de61b2011-01-16 13:04:51 -0800552 exec.execute(mFuture);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800553
554 return this;
555 }
556
557 /**
Dianne Hackborn96438cd2011-01-25 21:42:37 -0800558 * Convenience version of {@link #execute(Object...)} for use with
559 * a simple Runnable object.
Joe Onorato81de61b2011-01-16 13:04:51 -0800560 */
561 public static void execute(Runnable runnable) {
Dianne Hackborn96438cd2011-01-25 21:42:37 -0800562 THREAD_POOL_EXECUTOR.execute(runnable);
Joe Onorato81de61b2011-01-16 13:04:51 -0800563 }
564
565 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800566 * 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.
Dmitri Plotnikovbef9c7a2010-06-16 15:38:07 -0700570 *
Romain Guy4aaf8ec2010-06-03 10:56:41 -0700571 * {@link #onProgressUpdate} will note be called if the task has been
572 * canceled.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800573 *
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) {
Romain Guy4aaf8ec2010-06-03 10:56:41 -0700580 if (!isCancelled()) {
581 sHandler.obtainMessage(MESSAGE_POST_PROGRESS,
582 new AsyncTaskResult<Progress>(this, values)).sendToTarget();
583 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800584 }
585
586 private void finish(Result result) {
Romain Guye95003e2011-01-09 13:53:06 -0800587 if (isCancelled()) {
Romain Guy5ba812b2011-01-10 13:33:12 -0800588 onCancelled(result);
Romain Guye95003e2011-01-09 13:53:06 -0800589 } else {
590 onPostExecute(result);
591 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800592 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;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800608 }
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}