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