The Android Open Source Project | 9066cfe | 2009-03-03 19:31:44 -0800 | [diff] [blame] | 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 | |
| 17 | package android.os; |
| 18 | |
Joe Onorato | 81de61b | 2011-01-16 13:04:51 -0800 | [diff] [blame] | 19 | import java.util.ArrayDeque; |
The Android Open Source Project | 9066cfe | 2009-03-03 19:31:44 -0800 | [diff] [blame] | 20 | import java.util.concurrent.BlockingQueue; |
Gilles Debunne | 7f4b684 | 2010-04-27 17:54:21 -0700 | [diff] [blame] | 21 | import java.util.concurrent.Callable; |
| 22 | import java.util.concurrent.CancellationException; |
Joe Onorato | 81de61b | 2011-01-16 13:04:51 -0800 | [diff] [blame] | 23 | import java.util.concurrent.Executor; |
Gilles Debunne | 7f4b684 | 2010-04-27 17:54:21 -0700 | [diff] [blame] | 24 | import java.util.concurrent.ExecutionException; |
| 25 | import java.util.concurrent.FutureTask; |
The Android Open Source Project | 9066cfe | 2009-03-03 19:31:44 -0800 | [diff] [blame] | 26 | import java.util.concurrent.LinkedBlockingQueue; |
| 27 | import java.util.concurrent.ThreadFactory; |
Gilles Debunne | 7f4b684 | 2010-04-27 17:54:21 -0700 | [diff] [blame] | 28 | import java.util.concurrent.ThreadPoolExecutor; |
| 29 | import java.util.concurrent.TimeUnit; |
The Android Open Source Project | 9066cfe | 2009-03-03 19:31:44 -0800 | [diff] [blame] | 30 | import java.util.concurrent.TimeoutException; |
Romain Guy | 5ba812b | 2011-01-10 13:33:12 -0800 | [diff] [blame] | 31 | import java.util.concurrent.atomic.AtomicBoolean; |
The Android Open Source Project | 9066cfe | 2009-03-03 19:31:44 -0800 | [diff] [blame] | 32 | import 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 Debunne | 7f4b684 | 2010-04-27 17:54:21 -0700 | [diff] [blame] | 42 | * and 4 steps, called <code>onPreExecute</code>, <code>doInBackground</code>, |
| 43 | * <code>onProgressUpdate</code> and <code>onPostExecute</code>.</p> |
The Android Open Source Project | 9066cfe | 2009-03-03 19:31:44 -0800 | [diff] [blame] | 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> |
Owen Lin | 202f560 | 2009-12-28 15:54:23 +0800 | [diff] [blame] | 88 | * <p>Not all types are always used by an asynchronous task. To mark a type as unused, |
The Android Open Source Project | 9066cfe | 2009-03-03 19:31:44 -0800 | [diff] [blame] | 89 | * simply use the type {@link Void}:</p> |
| 90 | * <pre> |
Romain Guy | 6a1ae64 | 2009-05-02 22:52:17 -0700 | [diff] [blame] | 91 | * private class MyTask extends AsyncTask<Void, Void, Void> { ... } |
The Android Open Source Project | 9066cfe | 2009-03-03 19:31:44 -0800 | [diff] [blame] | 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> |
Romain Guy | e95003e | 2011-01-09 13:53:06 -0800 | [diff] [blame] | 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. |
Romain Guy | 5ba812b | 2011-01-10 13:33:12 -0800 | [diff] [blame] | 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> |
The Android Open Source Project | 9066cfe | 2009-03-03 19:31:44 -0800 | [diff] [blame] | 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> |
Makoto Onuki | aa60a02 | 2010-08-31 09:42:12 -0700 | [diff] [blame] | 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> |
The Android Open Source Project | 9066cfe | 2009-03-03 19:31:44 -0800 | [diff] [blame] | 148 | */ |
| 149 | public abstract class AsyncTask<Params, Progress, Result> { |
| 150 | private static final String LOG_TAG = "AsyncTask"; |
| 151 | |
Romain Guy | a9be47c | 2009-06-26 10:34:20 -0700 | [diff] [blame] | 152 | private static final int CORE_POOL_SIZE = 5; |
| 153 | private static final int MAXIMUM_POOL_SIZE = 128; |
Romain Guy | 6b424f4 | 2010-09-14 11:30:27 -0700 | [diff] [blame] | 154 | private static final int KEEP_ALIVE = 1; |
The Android Open Source Project | 9066cfe | 2009-03-03 19:31:44 -0800 | [diff] [blame] | 155 | |
The Android Open Source Project | 9066cfe | 2009-03-03 19:31:44 -0800 | [diff] [blame] | 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 | |
Joe Onorato | 81de61b | 2011-01-16 13:04:51 -0800 | [diff] [blame] | 164 | private static final BlockingQueue<Runnable> sPoolWorkQueue = |
| 165 | new LinkedBlockingQueue<Runnable>(10); |
| 166 | |
| 167 | /** |
Dianne Hackborn | 96438cd | 2011-01-25 21:42:37 -0800 | [diff] [blame] | 168 | * An {@link Executor} that can be used to execute tasks in parallel. |
Joe Onorato | 81de61b | 2011-01-16 13:04:51 -0800 | [diff] [blame] | 169 | */ |
Dianne Hackborn | 96438cd | 2011-01-25 21:42:37 -0800 | [diff] [blame] | 170 | public static final Executor THREAD_POOL_EXECUTOR |
Joe Onorato | 81de61b | 2011-01-16 13:04:51 -0800 | [diff] [blame] | 171 | = new ThreadPoolExecutor(CORE_POOL_SIZE, MAXIMUM_POOL_SIZE, KEEP_ALIVE, |
| 172 | TimeUnit.SECONDS, sPoolWorkQueue, sThreadFactory); |
| 173 | |
Dianne Hackborn | 96438cd | 2011-01-25 21:42:37 -0800 | [diff] [blame] | 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(); |
The Android Open Source Project | 9066cfe | 2009-03-03 19:31:44 -0800 | [diff] [blame] | 179 | |
| 180 | private static final int MESSAGE_POST_RESULT = 0x1; |
| 181 | private static final int MESSAGE_POST_PROGRESS = 0x2; |
The Android Open Source Project | 9066cfe | 2009-03-03 19:31:44 -0800 | [diff] [blame] | 182 | |
| 183 | private static final InternalHandler sHandler = new InternalHandler(); |
| 184 | |
Joe Onorato | d630f10 | 2011-03-17 18:42:26 -0700 | [diff] [blame] | 185 | private static volatile Executor sDefaultExecutor = SERIAL_EXECUTOR; |
The Android Open Source Project | 9066cfe | 2009-03-03 19:31:44 -0800 | [diff] [blame] | 186 | private final WorkerRunnable<Params, Result> mWorker; |
| 187 | private final FutureTask<Result> mFuture; |
| 188 | |
| 189 | private volatile Status mStatus = Status.PENDING; |
Romain Guy | 5ba812b | 2011-01-10 13:33:12 -0800 | [diff] [blame] | 190 | |
| 191 | private final AtomicBoolean mTaskInvoked = new AtomicBoolean(); |
The Android Open Source Project | 9066cfe | 2009-03-03 19:31:44 -0800 | [diff] [blame] | 192 | |
Joe Onorato | 81de61b | 2011-01-16 13:04:51 -0800 | [diff] [blame] | 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 | |
The Android Open Source Project | 9066cfe | 2009-03-03 19:31:44 -0800 | [diff] [blame] | 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 | |
Dianne Hackborn | 23fdaf6 | 2010-08-06 12:16:55 -0700 | [diff] [blame] | 238 | /** @hide Used to force static handler to be created. */ |
| 239 | public static void init() { |
| 240 | sHandler.getLooper(); |
| 241 | } |
| 242 | |
Joe Onorato | d630f10 | 2011-03-17 18:42:26 -0700 | [diff] [blame] | 243 | /** @hide */ |
| 244 | public static void setDefaultExecutor(Executor exec) { |
| 245 | sDefaultExecutor = exec; |
| 246 | } |
| 247 | |
The Android Open Source Project | 9066cfe | 2009-03-03 19:31:44 -0800 | [diff] [blame] | 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 { |
Romain Guy | 5ba812b | 2011-01-10 13:33:12 -0800 | [diff] [blame] | 254 | mTaskInvoked.set(true); |
| 255 | |
The Android Open Source Project | 9066cfe | 2009-03-03 19:31:44 -0800 | [diff] [blame] | 256 | Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); |
Romain Guy | 5ba812b | 2011-01-10 13:33:12 -0800 | [diff] [blame] | 257 | return postResult(doInBackground(mParams)); |
The Android Open Source Project | 9066cfe | 2009-03-03 19:31:44 -0800 | [diff] [blame] | 258 | } |
| 259 | }; |
| 260 | |
| 261 | mFuture = new FutureTask<Result>(mWorker) { |
| 262 | @Override |
| 263 | protected void done() { |
The Android Open Source Project | 9066cfe | 2009-03-03 19:31:44 -0800 | [diff] [blame] | 264 | try { |
Romain Guy | 5ba812b | 2011-01-10 13:33:12 -0800 | [diff] [blame] | 265 | final Result result = get(); |
| 266 | |
| 267 | postResultIfNotInvoked(result); |
The Android Open Source Project | 9066cfe | 2009-03-03 19:31:44 -0800 | [diff] [blame] | 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) { |
Romain Guy | 5ba812b | 2011-01-10 13:33:12 -0800 | [diff] [blame] | 274 | postResultIfNotInvoked(null); |
The Android Open Source Project | 9066cfe | 2009-03-03 19:31:44 -0800 | [diff] [blame] | 275 | } catch (Throwable t) { |
| 276 | throw new RuntimeException("An error occured while executing " |
| 277 | + "doInBackground()", t); |
| 278 | } |
The Android Open Source Project | 9066cfe | 2009-03-03 19:31:44 -0800 | [diff] [blame] | 279 | } |
| 280 | }; |
| 281 | } |
| 282 | |
Romain Guy | 5ba812b | 2011-01-10 13:33:12 -0800 | [diff] [blame] | 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 | |
The Android Open Source Project | 9066cfe | 2009-03-03 19:31:44 -0800 | [diff] [blame] | 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 | /** |
Romain Guy | e95003e | 2011-01-09 13:53:06 -0800 | [diff] [blame] | 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> |
The Android Open Source Project | 9066cfe | 2009-03-03 19:31:44 -0800 | [diff] [blame] | 338 | * |
| 339 | * @param result The result of the operation computed by {@link #doInBackground}. |
| 340 | * |
| 341 | * @see #onPreExecute |
| 342 | * @see #doInBackground |
Romain Guy | 5ba812b | 2011-01-10 13:33:12 -0800 | [diff] [blame] | 343 | * @see #onCancelled(Object) |
The Android Open Source Project | 9066cfe | 2009-03-03 19:31:44 -0800 | [diff] [blame] | 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 | /** |
Romain Guy | 5ba812b | 2011-01-10 13:33:12 -0800 | [diff] [blame] | 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> |
The Android Open Source Project | 9066cfe | 2009-03-03 19:31:44 -0800 | [diff] [blame] | 369 | * |
Romain Guy | 5ba812b | 2011-01-10 13:33:12 -0800 | [diff] [blame] | 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) |
The Android Open Source Project | 9066cfe | 2009-03-03 19:31:44 -0800 | [diff] [blame] | 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 |
Romain Guy | e95003e | 2011-01-09 13:53:06 -0800 | [diff] [blame] | 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. |
The Android Open Source Project | 9066cfe | 2009-03-03 19:31:44 -0800 | [diff] [blame] | 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 | /** |
Romain Guy | e95003e | 2011-01-09 13:53:06 -0800 | [diff] [blame] | 411 | * <p>Attempts to cancel execution of this task. This attempt will |
The Android Open Source Project | 9066cfe | 2009-03-03 19:31:44 -0800 | [diff] [blame] | 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, |
Romain Guy | e95003e | 2011-01-09 13:53:06 -0800 | [diff] [blame] | 415 | * this task should never run. If the task has already started, |
The Android Open Source Project | 9066cfe | 2009-03-03 19:31:44 -0800 | [diff] [blame] | 416 | * then the <tt>mayInterruptIfRunning</tt> parameter determines |
| 417 | * whether the thread executing this task should be interrupted in |
Romain Guy | e95003e | 2011-01-09 13:53:06 -0800 | [diff] [blame] | 418 | * an attempt to stop the task.</p> |
| 419 | * |
Romain Guy | 5ba812b | 2011-01-10 13:33:12 -0800 | [diff] [blame] | 420 | * <p>Calling this method will result in {@link #onCancelled(Object)} being |
Romain Guy | e95003e | 2011-01-09 13:53:06 -0800 | [diff] [blame] | 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> |
The Android Open Source Project | 9066cfe | 2009-03-03 19:31:44 -0800 | [diff] [blame] | 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() |
Romain Guy | 5ba812b | 2011-01-10 13:33:12 -0800 | [diff] [blame] | 437 | * @see #onCancelled(Object) |
The Android Open Source Project | 9066cfe | 2009-03-03 19:31:44 -0800 | [diff] [blame] | 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 |
Dianne Hackborn | 96438cd | 2011-01-25 21:42:37 -0800 | [diff] [blame] | 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. |
The Android Open Source Project | 9066cfe | 2009-03-03 19:31:44 -0800 | [diff] [blame] | 493 | * |
Dianne Hackborn | 96438cd | 2011-01-25 21:42:37 -0800 | [diff] [blame] | 494 | * <p>This method must be invoked on the UI thread. |
The Android Open Source Project | 9066cfe | 2009-03-03 19:31:44 -0800 | [diff] [blame] | 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) { |
Joe Onorato | d630f10 | 2011-03-17 18:42:26 -0700 | [diff] [blame] | 504 | return executeOnExecutor(sDefaultExecutor, params); |
Joe Onorato | 81de61b | 2011-01-16 13:04:51 -0800 | [diff] [blame] | 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. |
Dianne Hackborn | 96438cd | 2011-01-25 21:42:37 -0800 | [diff] [blame] | 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}. |
Joe Onorato | 81de61b | 2011-01-16 13:04:51 -0800 | [diff] [blame] | 526 | * |
Dianne Hackborn | 96438cd | 2011-01-25 21:42:37 -0800 | [diff] [blame] | 527 | * <p>This method must be invoked on the UI thread. |
Joe Onorato | 81de61b | 2011-01-16 13:04:51 -0800 | [diff] [blame] | 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) { |
The Android Open Source Project | 9066cfe | 2009-03-03 19:31:44 -0800 | [diff] [blame] | 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; |
Joe Onorato | 81de61b | 2011-01-16 13:04:51 -0800 | [diff] [blame] | 557 | exec.execute(mFuture); |
The Android Open Source Project | 9066cfe | 2009-03-03 19:31:44 -0800 | [diff] [blame] | 558 | |
| 559 | return this; |
| 560 | } |
| 561 | |
| 562 | /** |
Dianne Hackborn | 96438cd | 2011-01-25 21:42:37 -0800 | [diff] [blame] | 563 | * Convenience version of {@link #execute(Object...)} for use with |
| 564 | * a simple Runnable object. |
Joe Onorato | 81de61b | 2011-01-16 13:04:51 -0800 | [diff] [blame] | 565 | */ |
| 566 | public static void execute(Runnable runnable) { |
Joe Onorato | d630f10 | 2011-03-17 18:42:26 -0700 | [diff] [blame] | 567 | sDefaultExecutor.execute(runnable); |
Joe Onorato | 81de61b | 2011-01-16 13:04:51 -0800 | [diff] [blame] | 568 | } |
| 569 | |
| 570 | /** |
The Android Open Source Project | 9066cfe | 2009-03-03 19:31:44 -0800 | [diff] [blame] | 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. |
Dmitri Plotnikov | bef9c7a | 2010-06-16 15:38:07 -0700 | [diff] [blame] | 575 | * |
Romain Guy | 4aaf8ec | 2010-06-03 10:56:41 -0700 | [diff] [blame] | 576 | * {@link #onProgressUpdate} will note be called if the task has been |
| 577 | * canceled. |
The Android Open Source Project | 9066cfe | 2009-03-03 19:31:44 -0800 | [diff] [blame] | 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) { |
Romain Guy | 4aaf8ec | 2010-06-03 10:56:41 -0700 | [diff] [blame] | 585 | if (!isCancelled()) { |
| 586 | sHandler.obtainMessage(MESSAGE_POST_PROGRESS, |
| 587 | new AsyncTaskResult<Progress>(this, values)).sendToTarget(); |
| 588 | } |
The Android Open Source Project | 9066cfe | 2009-03-03 19:31:44 -0800 | [diff] [blame] | 589 | } |
| 590 | |
| 591 | private void finish(Result result) { |
Romain Guy | e95003e | 2011-01-09 13:53:06 -0800 | [diff] [blame] | 592 | if (isCancelled()) { |
Romain Guy | 5ba812b | 2011-01-10 13:33:12 -0800 | [diff] [blame] | 593 | onCancelled(result); |
Romain Guy | e95003e | 2011-01-09 13:53:06 -0800 | [diff] [blame] | 594 | } else { |
| 595 | onPostExecute(result); |
| 596 | } |
The Android Open Source Project | 9066cfe | 2009-03-03 19:31:44 -0800 | [diff] [blame] | 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; |
The Android Open Source Project | 9066cfe | 2009-03-03 19:31:44 -0800 | [diff] [blame] | 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 | } |