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 | |
Tor Norbye | 83c6896 | 2015-03-10 20:55:31 -0700 | [diff] [blame] | 19 | import android.annotation.MainThread; |
Makoto Onuki | 1488a3a | 2017-05-24 12:25:46 -0700 | [diff] [blame] | 20 | import android.annotation.Nullable; |
Tor Norbye | 83c6896 | 2015-03-10 20:55:31 -0700 | [diff] [blame] | 21 | import android.annotation.WorkerThread; |
Joe Onorato | 81de61b | 2011-01-16 13:04:51 -0800 | [diff] [blame] | 22 | import java.util.ArrayDeque; |
The Android Open Source Project | 9066cfe | 2009-03-03 19:31:44 -0800 | [diff] [blame] | 23 | import java.util.concurrent.BlockingQueue; |
Gilles Debunne | 7f4b684 | 2010-04-27 17:54:21 -0700 | [diff] [blame] | 24 | import java.util.concurrent.Callable; |
| 25 | import java.util.concurrent.CancellationException; |
| 26 | import java.util.concurrent.ExecutionException; |
Makoto Onuki | 1488a3a | 2017-05-24 12:25:46 -0700 | [diff] [blame] | 27 | import java.util.concurrent.Executor; |
Gilles Debunne | 7f4b684 | 2010-04-27 17:54:21 -0700 | [diff] [blame] | 28 | import java.util.concurrent.FutureTask; |
The Android Open Source Project | 9066cfe | 2009-03-03 19:31:44 -0800 | [diff] [blame] | 29 | import java.util.concurrent.LinkedBlockingQueue; |
| 30 | import java.util.concurrent.ThreadFactory; |
Gilles Debunne | 7f4b684 | 2010-04-27 17:54:21 -0700 | [diff] [blame] | 31 | import java.util.concurrent.ThreadPoolExecutor; |
| 32 | import java.util.concurrent.TimeUnit; |
The Android Open Source Project | 9066cfe | 2009-03-03 19:31:44 -0800 | [diff] [blame] | 33 | import java.util.concurrent.TimeoutException; |
Romain Guy | 5ba812b | 2011-01-10 13:33:12 -0800 | [diff] [blame] | 34 | import java.util.concurrent.atomic.AtomicBoolean; |
The Android Open Source Project | 9066cfe | 2009-03-03 19:31:44 -0800 | [diff] [blame] | 35 | import java.util.concurrent.atomic.AtomicInteger; |
| 36 | |
| 37 | /** |
Mark Lu | 53415ff | 2016-08-12 13:02:32 -0700 | [diff] [blame] | 38 | * <p>AsyncTask enables proper and easy use of the UI thread. This class allows you |
| 39 | * to perform background operations and publish results on the UI thread without |
Romain Guy | 0bbd8d8 | 2011-10-11 18:13:37 -0700 | [diff] [blame] | 40 | * having to manipulate threads and/or handlers.</p> |
The Android Open Source Project | 9066cfe | 2009-03-03 19:31:44 -0800 | [diff] [blame] | 41 | * |
Romain Guy | 2c1b8c7 | 2012-05-21 10:43:26 -0700 | [diff] [blame] | 42 | * <p>AsyncTask is designed to be a helper class around {@link Thread} and {@link Handler} |
| 43 | * and does not constitute a generic threading framework. AsyncTasks should ideally be |
| 44 | * used for short operations (a few seconds at the most.) If you need to keep threads |
| 45 | * running for long periods of time, it is highly recommended you use the various APIs |
Patrick Tjin | 72fa3ed | 2014-02-25 14:52:23 -0800 | [diff] [blame] | 46 | * provided by the <code>java.util.concurrent</code> package such as {@link Executor}, |
Romain Guy | 2c1b8c7 | 2012-05-21 10:43:26 -0700 | [diff] [blame] | 47 | * {@link ThreadPoolExecutor} and {@link FutureTask}.</p> |
| 48 | * |
The Android Open Source Project | 9066cfe | 2009-03-03 19:31:44 -0800 | [diff] [blame] | 49 | * <p>An asynchronous task is defined by a computation that runs on a background thread and |
Romain Guy | 0bbd8d8 | 2011-10-11 18:13:37 -0700 | [diff] [blame] | 50 | * whose result is published on the UI thread. An asynchronous task is defined by 3 generic |
The Android Open Source Project | 9066cfe | 2009-03-03 19:31:44 -0800 | [diff] [blame] | 51 | * types, called <code>Params</code>, <code>Progress</code> and <code>Result</code>, |
Gilles Debunne | 7f4b684 | 2010-04-27 17:54:21 -0700 | [diff] [blame] | 52 | * and 4 steps, called <code>onPreExecute</code>, <code>doInBackground</code>, |
| 53 | * <code>onProgressUpdate</code> and <code>onPostExecute</code>.</p> |
The Android Open Source Project | 9066cfe | 2009-03-03 19:31:44 -0800 | [diff] [blame] | 54 | * |
Joe Fernandez | b54e7a3 | 2011-10-03 15:09:50 -0700 | [diff] [blame] | 55 | * <div class="special reference"> |
| 56 | * <h3>Developer Guides</h3> |
| 57 | * <p>For more information about using tasks and threads, read the |
Mark Lu | 53415ff | 2016-08-12 13:02:32 -0700 | [diff] [blame] | 58 | * <a href="{@docRoot}guide/components/processes-and-threads.html">Processes and |
Joe Fernandez | b54e7a3 | 2011-10-03 15:09:50 -0700 | [diff] [blame] | 59 | * Threads</a> developer guide.</p> |
| 60 | * </div> |
| 61 | * |
The Android Open Source Project | 9066cfe | 2009-03-03 19:31:44 -0800 | [diff] [blame] | 62 | * <h2>Usage</h2> |
| 63 | * <p>AsyncTask must be subclassed to be used. The subclass will override at least |
| 64 | * one method ({@link #doInBackground}), and most often will override a |
| 65 | * second one ({@link #onPostExecute}.)</p> |
| 66 | * |
| 67 | * <p>Here is an example of subclassing:</p> |
| 68 | * <pre class="prettyprint"> |
| 69 | * private class DownloadFilesTask extends AsyncTask<URL, Integer, Long> { |
| 70 | * protected Long doInBackground(URL... urls) { |
| 71 | * int count = urls.length; |
| 72 | * long totalSize = 0; |
| 73 | * for (int i = 0; i < count; i++) { |
| 74 | * totalSize += Downloader.downloadFile(urls[i]); |
| 75 | * publishProgress((int) ((i / (float) count) * 100)); |
Romain Guy | 2c1b8c7 | 2012-05-21 10:43:26 -0700 | [diff] [blame] | 76 | * // Escape early if cancel() is called |
| 77 | * if (isCancelled()) break; |
The Android Open Source Project | 9066cfe | 2009-03-03 19:31:44 -0800 | [diff] [blame] | 78 | * } |
| 79 | * return totalSize; |
| 80 | * } |
| 81 | * |
| 82 | * protected void onProgressUpdate(Integer... progress) { |
| 83 | * setProgressPercent(progress[0]); |
| 84 | * } |
| 85 | * |
| 86 | * protected void onPostExecute(Long result) { |
| 87 | * showDialog("Downloaded " + result + " bytes"); |
| 88 | * } |
| 89 | * } |
| 90 | * </pre> |
| 91 | * |
| 92 | * <p>Once created, a task is executed very simply:</p> |
| 93 | * <pre class="prettyprint"> |
| 94 | * new DownloadFilesTask().execute(url1, url2, url3); |
| 95 | * </pre> |
| 96 | * |
| 97 | * <h2>AsyncTask's generic types</h2> |
| 98 | * <p>The three types used by an asynchronous task are the following:</p> |
| 99 | * <ol> |
| 100 | * <li><code>Params</code>, the type of the parameters sent to the task upon |
| 101 | * execution.</li> |
| 102 | * <li><code>Progress</code>, the type of the progress units published during |
| 103 | * the background computation.</li> |
| 104 | * <li><code>Result</code>, the type of the result of the background |
| 105 | * computation.</li> |
| 106 | * </ol> |
Owen Lin | 202f560 | 2009-12-28 15:54:23 +0800 | [diff] [blame] | 107 | * <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] | 108 | * simply use the type {@link Void}:</p> |
| 109 | * <pre> |
Romain Guy | 6a1ae64 | 2009-05-02 22:52:17 -0700 | [diff] [blame] | 110 | * private class MyTask extends AsyncTask<Void, Void, Void> { ... } |
The Android Open Source Project | 9066cfe | 2009-03-03 19:31:44 -0800 | [diff] [blame] | 111 | * </pre> |
| 112 | * |
| 113 | * <h2>The 4 steps</h2> |
| 114 | * <p>When an asynchronous task is executed, the task goes through 4 steps:</p> |
| 115 | * <ol> |
Romain Guy | 6f931cc | 2012-10-17 11:06:11 -0700 | [diff] [blame] | 116 | * <li>{@link #onPreExecute()}, invoked on the UI thread before the task |
The Android Open Source Project | 9066cfe | 2009-03-03 19:31:44 -0800 | [diff] [blame] | 117 | * is executed. This step is normally used to setup the task, for instance by |
| 118 | * showing a progress bar in the user interface.</li> |
| 119 | * <li>{@link #doInBackground}, invoked on the background thread |
| 120 | * immediately after {@link #onPreExecute()} finishes executing. This step is used |
| 121 | * to perform background computation that can take a long time. The parameters |
| 122 | * of the asynchronous task are passed to this step. The result of the computation must |
| 123 | * be returned by this step and will be passed back to the last step. This step |
| 124 | * can also use {@link #publishProgress} to publish one or more units |
Romain Guy | 0bbd8d8 | 2011-10-11 18:13:37 -0700 | [diff] [blame] | 125 | * of progress. These values are published on the UI thread, in the |
The Android Open Source Project | 9066cfe | 2009-03-03 19:31:44 -0800 | [diff] [blame] | 126 | * {@link #onProgressUpdate} step.</li> |
Romain Guy | 0bbd8d8 | 2011-10-11 18:13:37 -0700 | [diff] [blame] | 127 | * <li>{@link #onProgressUpdate}, invoked on the UI thread after a |
The Android Open Source Project | 9066cfe | 2009-03-03 19:31:44 -0800 | [diff] [blame] | 128 | * call to {@link #publishProgress}. The timing of the execution is |
| 129 | * undefined. This method is used to display any form of progress in the user |
| 130 | * interface while the background computation is still executing. For instance, |
| 131 | * it can be used to animate a progress bar or show logs in a text field.</li> |
Romain Guy | 0bbd8d8 | 2011-10-11 18:13:37 -0700 | [diff] [blame] | 132 | * <li>{@link #onPostExecute}, invoked on the UI thread after the background |
The Android Open Source Project | 9066cfe | 2009-03-03 19:31:44 -0800 | [diff] [blame] | 133 | * computation finishes. The result of the background computation is passed to |
| 134 | * this step as a parameter.</li> |
| 135 | * </ol> |
Romain Guy | e95003e | 2011-01-09 13:53:06 -0800 | [diff] [blame] | 136 | * |
| 137 | * <h2>Cancelling a task</h2> |
| 138 | * <p>A task can be cancelled at any time by invoking {@link #cancel(boolean)}. Invoking |
| 139 | * this method will cause subsequent calls to {@link #isCancelled()} to return true. |
Romain Guy | 5ba812b | 2011-01-10 13:33:12 -0800 | [diff] [blame] | 140 | * After invoking this method, {@link #onCancelled(Object)}, instead of |
| 141 | * {@link #onPostExecute(Object)} will be invoked after {@link #doInBackground(Object[])} |
| 142 | * returns. To ensure that a task is cancelled as quickly as possible, you should always |
| 143 | * check the return value of {@link #isCancelled()} periodically from |
| 144 | * {@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] | 145 | * |
| 146 | * <h2>Threading rules</h2> |
| 147 | * <p>There are a few threading rules that must be followed for this class to |
| 148 | * work properly:</p> |
| 149 | * <ul> |
Romain Guy | 5e9120d | 2012-01-30 12:17:22 -0800 | [diff] [blame] | 150 | * <li>The AsyncTask class must be loaded on the UI thread. This is done |
| 151 | * automatically as of {@link android.os.Build.VERSION_CODES#JELLY_BEAN}.</li> |
Romain Guy | 0bbd8d8 | 2011-10-11 18:13:37 -0700 | [diff] [blame] | 152 | * <li>The task instance must be created on the UI thread.</li> |
| 153 | * <li>{@link #execute} must be invoked on the UI thread.</li> |
The Android Open Source Project | 9066cfe | 2009-03-03 19:31:44 -0800 | [diff] [blame] | 154 | * <li>Do not call {@link #onPreExecute()}, {@link #onPostExecute}, |
| 155 | * {@link #doInBackground}, {@link #onProgressUpdate} manually.</li> |
| 156 | * <li>The task can be executed only once (an exception will be thrown if |
| 157 | * a second execution is attempted.)</li> |
| 158 | * </ul> |
Makoto Onuki | aa60a02 | 2010-08-31 09:42:12 -0700 | [diff] [blame] | 159 | * |
| 160 | * <h2>Memory observability</h2> |
| 161 | * <p>AsyncTask guarantees that all callback calls are synchronized in such a way that the following |
| 162 | * operations are safe without explicit synchronizations.</p> |
| 163 | * <ul> |
| 164 | * <li>Set member fields in the constructor or {@link #onPreExecute}, and refer to them |
| 165 | * in {@link #doInBackground}. |
| 166 | * <li>Set member fields in {@link #doInBackground}, and refer to them in |
| 167 | * {@link #onProgressUpdate} and {@link #onPostExecute}. |
| 168 | * </ul> |
Romain Guy | 2c1b8c7 | 2012-05-21 10:43:26 -0700 | [diff] [blame] | 169 | * |
| 170 | * <h2>Order of execution</h2> |
| 171 | * <p>When first introduced, AsyncTasks were executed serially on a single background |
| 172 | * thread. Starting with {@link android.os.Build.VERSION_CODES#DONUT}, this was changed |
| 173 | * to a pool of threads allowing multiple tasks to operate in parallel. Starting with |
| 174 | * {@link android.os.Build.VERSION_CODES#HONEYCOMB}, tasks are executed on a single |
| 175 | * thread to avoid common application errors caused by parallel execution.</p> |
| 176 | * <p>If you truly want parallel execution, you can invoke |
| 177 | * {@link #executeOnExecutor(java.util.concurrent.Executor, Object[])} with |
| 178 | * {@link #THREAD_POOL_EXECUTOR}.</p> |
The Android Open Source Project | 9066cfe | 2009-03-03 19:31:44 -0800 | [diff] [blame] | 179 | */ |
| 180 | public abstract class AsyncTask<Params, Progress, Result> { |
| 181 | private static final String LOG_TAG = "AsyncTask"; |
| 182 | |
Romain Guy | 719c44e | 2013-08-09 16:09:44 -0700 | [diff] [blame] | 183 | private static final int CPU_COUNT = Runtime.getRuntime().availableProcessors(); |
John Reck | 2b0ebb3 | 2015-11-30 15:45:25 -0800 | [diff] [blame] | 184 | // We want at least 2 threads and at most 4 threads in the core pool, |
| 185 | // preferring to have 1 less than the CPU count to avoid saturating |
| 186 | // the CPU with background work |
| 187 | private static final int CORE_POOL_SIZE = Math.max(2, Math.min(CPU_COUNT - 1, 4)); |
Romain Guy | 719c44e | 2013-08-09 16:09:44 -0700 | [diff] [blame] | 188 | private static final int MAXIMUM_POOL_SIZE = CPU_COUNT * 2 + 1; |
John Reck | 2b0ebb3 | 2015-11-30 15:45:25 -0800 | [diff] [blame] | 189 | private static final int KEEP_ALIVE_SECONDS = 30; |
The Android Open Source Project | 9066cfe | 2009-03-03 19:31:44 -0800 | [diff] [blame] | 190 | |
The Android Open Source Project | 9066cfe | 2009-03-03 19:31:44 -0800 | [diff] [blame] | 191 | private static final ThreadFactory sThreadFactory = new ThreadFactory() { |
| 192 | private final AtomicInteger mCount = new AtomicInteger(1); |
| 193 | |
| 194 | public Thread newThread(Runnable r) { |
| 195 | return new Thread(r, "AsyncTask #" + mCount.getAndIncrement()); |
| 196 | } |
| 197 | }; |
| 198 | |
Joe Onorato | 81de61b | 2011-01-16 13:04:51 -0800 | [diff] [blame] | 199 | private static final BlockingQueue<Runnable> sPoolWorkQueue = |
Romain Guy | 719c44e | 2013-08-09 16:09:44 -0700 | [diff] [blame] | 200 | new LinkedBlockingQueue<Runnable>(128); |
Joe Onorato | 81de61b | 2011-01-16 13:04:51 -0800 | [diff] [blame] | 201 | |
| 202 | /** |
Dianne Hackborn | 96438cd | 2011-01-25 21:42:37 -0800 | [diff] [blame] | 203 | * An {@link Executor} that can be used to execute tasks in parallel. |
Joe Onorato | 81de61b | 2011-01-16 13:04:51 -0800 | [diff] [blame] | 204 | */ |
John Reck | 2b0ebb3 | 2015-11-30 15:45:25 -0800 | [diff] [blame] | 205 | public static final Executor THREAD_POOL_EXECUTOR; |
| 206 | |
| 207 | static { |
| 208 | ThreadPoolExecutor threadPoolExecutor = new ThreadPoolExecutor( |
| 209 | CORE_POOL_SIZE, MAXIMUM_POOL_SIZE, KEEP_ALIVE_SECONDS, TimeUnit.SECONDS, |
| 210 | sPoolWorkQueue, sThreadFactory); |
| 211 | threadPoolExecutor.allowCoreThreadTimeOut(true); |
| 212 | THREAD_POOL_EXECUTOR = threadPoolExecutor; |
| 213 | } |
Joe Onorato | 81de61b | 2011-01-16 13:04:51 -0800 | [diff] [blame] | 214 | |
Dianne Hackborn | 96438cd | 2011-01-25 21:42:37 -0800 | [diff] [blame] | 215 | /** |
| 216 | * An {@link Executor} that executes tasks one at a time in serial |
| 217 | * order. This serialization is global to a particular process. |
| 218 | */ |
| 219 | public static final Executor SERIAL_EXECUTOR = new SerialExecutor(); |
The Android Open Source Project | 9066cfe | 2009-03-03 19:31:44 -0800 | [diff] [blame] | 220 | |
| 221 | private static final int MESSAGE_POST_RESULT = 0x1; |
| 222 | private static final int MESSAGE_POST_PROGRESS = 0x2; |
The Android Open Source Project | 9066cfe | 2009-03-03 19:31:44 -0800 | [diff] [blame] | 223 | |
Joe Onorato | d630f10 | 2011-03-17 18:42:26 -0700 | [diff] [blame] | 224 | private static volatile Executor sDefaultExecutor = SERIAL_EXECUTOR; |
Jeff Brown | bba231d | 2014-11-14 15:49:45 -0800 | [diff] [blame] | 225 | private static InternalHandler sHandler; |
| 226 | |
The Android Open Source Project | 9066cfe | 2009-03-03 19:31:44 -0800 | [diff] [blame] | 227 | private final WorkerRunnable<Params, Result> mWorker; |
| 228 | private final FutureTask<Result> mFuture; |
| 229 | |
| 230 | private volatile Status mStatus = Status.PENDING; |
Romain Guy | 5ba812b | 2011-01-10 13:33:12 -0800 | [diff] [blame] | 231 | |
Romain Guy | 657f513 | 2011-12-05 14:49:33 -0800 | [diff] [blame] | 232 | private final AtomicBoolean mCancelled = new AtomicBoolean(); |
Romain Guy | 5ba812b | 2011-01-10 13:33:12 -0800 | [diff] [blame] | 233 | private final AtomicBoolean mTaskInvoked = new AtomicBoolean(); |
The Android Open Source Project | 9066cfe | 2009-03-03 19:31:44 -0800 | [diff] [blame] | 234 | |
Makoto Onuki | 1488a3a | 2017-05-24 12:25:46 -0700 | [diff] [blame] | 235 | private final Handler mHandler; |
| 236 | |
Joe Onorato | 81de61b | 2011-01-16 13:04:51 -0800 | [diff] [blame] | 237 | private static class SerialExecutor implements Executor { |
| 238 | final ArrayDeque<Runnable> mTasks = new ArrayDeque<Runnable>(); |
| 239 | Runnable mActive; |
| 240 | |
| 241 | public synchronized void execute(final Runnable r) { |
| 242 | mTasks.offer(new Runnable() { |
| 243 | public void run() { |
| 244 | try { |
| 245 | r.run(); |
| 246 | } finally { |
| 247 | scheduleNext(); |
| 248 | } |
| 249 | } |
| 250 | }); |
| 251 | if (mActive == null) { |
| 252 | scheduleNext(); |
| 253 | } |
| 254 | } |
| 255 | |
| 256 | protected synchronized void scheduleNext() { |
| 257 | if ((mActive = mTasks.poll()) != null) { |
| 258 | THREAD_POOL_EXECUTOR.execute(mActive); |
| 259 | } |
| 260 | } |
| 261 | } |
| 262 | |
The Android Open Source Project | 9066cfe | 2009-03-03 19:31:44 -0800 | [diff] [blame] | 263 | /** |
| 264 | * Indicates the current status of the task. Each status will be set only once |
| 265 | * during the lifetime of a task. |
| 266 | */ |
| 267 | public enum Status { |
| 268 | /** |
| 269 | * Indicates that the task has not been executed yet. |
| 270 | */ |
| 271 | PENDING, |
| 272 | /** |
| 273 | * Indicates that the task is running. |
| 274 | */ |
| 275 | RUNNING, |
| 276 | /** |
| 277 | * Indicates that {@link AsyncTask#onPostExecute} has finished. |
| 278 | */ |
| 279 | FINISHED, |
| 280 | } |
| 281 | |
Makoto Onuki | 1488a3a | 2017-05-24 12:25:46 -0700 | [diff] [blame] | 282 | private static Handler getMainHandler() { |
Jeff Brown | bba231d | 2014-11-14 15:49:45 -0800 | [diff] [blame] | 283 | synchronized (AsyncTask.class) { |
| 284 | if (sHandler == null) { |
Makoto Onuki | 1488a3a | 2017-05-24 12:25:46 -0700 | [diff] [blame] | 285 | sHandler = new InternalHandler(Looper.getMainLooper()); |
Jeff Brown | bba231d | 2014-11-14 15:49:45 -0800 | [diff] [blame] | 286 | } |
| 287 | return sHandler; |
| 288 | } |
Dianne Hackborn | 23fdaf6 | 2010-08-06 12:16:55 -0700 | [diff] [blame] | 289 | } |
| 290 | |
Makoto Onuki | 1488a3a | 2017-05-24 12:25:46 -0700 | [diff] [blame] | 291 | private Handler getHandler() { |
| 292 | return mHandler; |
| 293 | } |
| 294 | |
Joe Onorato | d630f10 | 2011-03-17 18:42:26 -0700 | [diff] [blame] | 295 | /** @hide */ |
| 296 | public static void setDefaultExecutor(Executor exec) { |
| 297 | sDefaultExecutor = exec; |
| 298 | } |
| 299 | |
The Android Open Source Project | 9066cfe | 2009-03-03 19:31:44 -0800 | [diff] [blame] | 300 | /** |
Romain Guy | 0bbd8d8 | 2011-10-11 18:13:37 -0700 | [diff] [blame] | 301 | * Creates a new asynchronous task. This constructor must be invoked on the UI thread. |
The Android Open Source Project | 9066cfe | 2009-03-03 19:31:44 -0800 | [diff] [blame] | 302 | */ |
| 303 | public AsyncTask() { |
Makoto Onuki | 1488a3a | 2017-05-24 12:25:46 -0700 | [diff] [blame] | 304 | this((Looper) null); |
| 305 | } |
| 306 | |
| 307 | /** |
| 308 | * Creates a new asynchronous task. This constructor must be invoked on the UI thread. |
| 309 | * |
| 310 | * @hide |
| 311 | */ |
| 312 | public AsyncTask(@Nullable Handler handler) { |
| 313 | this(handler != null ? handler.getLooper() : null); |
| 314 | } |
| 315 | |
| 316 | /** |
| 317 | * Creates a new asynchronous task. This constructor must be invoked on the UI thread. |
| 318 | * |
| 319 | * @hide |
| 320 | */ |
| 321 | public AsyncTask(@Nullable Looper callbackLooper) { |
| 322 | mHandler = callbackLooper == null || callbackLooper == Looper.getMainLooper() |
| 323 | ? getMainHandler() |
| 324 | : new Handler(callbackLooper); |
| 325 | |
The Android Open Source Project | 9066cfe | 2009-03-03 19:31:44 -0800 | [diff] [blame] | 326 | mWorker = new WorkerRunnable<Params, Result>() { |
| 327 | public Result call() throws Exception { |
Romain Guy | 5ba812b | 2011-01-10 13:33:12 -0800 | [diff] [blame] | 328 | mTaskInvoked.set(true); |
Tony Mantler | 78a8e9d | 2016-08-05 14:08:06 -0700 | [diff] [blame] | 329 | Result result = null; |
| 330 | try { |
| 331 | Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); |
| 332 | //noinspection unchecked |
| 333 | result = doInBackground(mParams); |
| 334 | Binder.flushPendingCommands(); |
Tony Mantler | 5eb91a4 | 2016-09-28 13:55:15 -0700 | [diff] [blame] | 335 | } catch (Throwable tr) { |
| 336 | mCancelled.set(true); |
| 337 | throw tr; |
Tony Mantler | 78a8e9d | 2016-08-05 14:08:06 -0700 | [diff] [blame] | 338 | } finally { |
| 339 | postResult(result); |
| 340 | } |
| 341 | return result; |
The Android Open Source Project | 9066cfe | 2009-03-03 19:31:44 -0800 | [diff] [blame] | 342 | } |
| 343 | }; |
| 344 | |
| 345 | mFuture = new FutureTask<Result>(mWorker) { |
| 346 | @Override |
| 347 | protected void done() { |
The Android Open Source Project | 9066cfe | 2009-03-03 19:31:44 -0800 | [diff] [blame] | 348 | try { |
Romain Guy | 657f513 | 2011-12-05 14:49:33 -0800 | [diff] [blame] | 349 | postResultIfNotInvoked(get()); |
The Android Open Source Project | 9066cfe | 2009-03-03 19:31:44 -0800 | [diff] [blame] | 350 | } catch (InterruptedException e) { |
| 351 | android.util.Log.w(LOG_TAG, e); |
| 352 | } catch (ExecutionException e) { |
Adrian Roos | 44bc07d | 2015-02-11 16:20:26 +0100 | [diff] [blame] | 353 | throw new RuntimeException("An error occurred while executing doInBackground()", |
The Android Open Source Project | 9066cfe | 2009-03-03 19:31:44 -0800 | [diff] [blame] | 354 | e.getCause()); |
| 355 | } catch (CancellationException e) { |
Romain Guy | 5ba812b | 2011-01-10 13:33:12 -0800 | [diff] [blame] | 356 | postResultIfNotInvoked(null); |
The Android Open Source Project | 9066cfe | 2009-03-03 19:31:44 -0800 | [diff] [blame] | 357 | } |
The Android Open Source Project | 9066cfe | 2009-03-03 19:31:44 -0800 | [diff] [blame] | 358 | } |
| 359 | }; |
| 360 | } |
| 361 | |
Romain Guy | 5ba812b | 2011-01-10 13:33:12 -0800 | [diff] [blame] | 362 | private void postResultIfNotInvoked(Result result) { |
| 363 | final boolean wasTaskInvoked = mTaskInvoked.get(); |
| 364 | if (!wasTaskInvoked) { |
| 365 | postResult(result); |
| 366 | } |
| 367 | } |
| 368 | |
| 369 | private Result postResult(Result result) { |
Romain Guy | 657f513 | 2011-12-05 14:49:33 -0800 | [diff] [blame] | 370 | @SuppressWarnings("unchecked") |
Jeff Brown | bba231d | 2014-11-14 15:49:45 -0800 | [diff] [blame] | 371 | Message message = getHandler().obtainMessage(MESSAGE_POST_RESULT, |
Romain Guy | 5ba812b | 2011-01-10 13:33:12 -0800 | [diff] [blame] | 372 | new AsyncTaskResult<Result>(this, result)); |
| 373 | message.sendToTarget(); |
| 374 | return result; |
| 375 | } |
| 376 | |
The Android Open Source Project | 9066cfe | 2009-03-03 19:31:44 -0800 | [diff] [blame] | 377 | /** |
| 378 | * Returns the current status of this task. |
| 379 | * |
| 380 | * @return The current status. |
| 381 | */ |
| 382 | public final Status getStatus() { |
| 383 | return mStatus; |
| 384 | } |
| 385 | |
| 386 | /** |
| 387 | * Override this method to perform a computation on a background thread. The |
| 388 | * specified parameters are the parameters passed to {@link #execute} |
| 389 | * by the caller of this task. |
| 390 | * |
| 391 | * This method can call {@link #publishProgress} to publish updates |
Romain Guy | 0bbd8d8 | 2011-10-11 18:13:37 -0700 | [diff] [blame] | 392 | * on the UI thread. |
The Android Open Source Project | 9066cfe | 2009-03-03 19:31:44 -0800 | [diff] [blame] | 393 | * |
| 394 | * @param params The parameters of the task. |
| 395 | * |
| 396 | * @return A result, defined by the subclass of this task. |
| 397 | * |
| 398 | * @see #onPreExecute() |
| 399 | * @see #onPostExecute |
| 400 | * @see #publishProgress |
| 401 | */ |
Tor Norbye | 83c6896 | 2015-03-10 20:55:31 -0700 | [diff] [blame] | 402 | @WorkerThread |
The Android Open Source Project | 9066cfe | 2009-03-03 19:31:44 -0800 | [diff] [blame] | 403 | protected abstract Result doInBackground(Params... params); |
| 404 | |
| 405 | /** |
Romain Guy | 0bbd8d8 | 2011-10-11 18:13:37 -0700 | [diff] [blame] | 406 | * Runs on the UI thread before {@link #doInBackground}. |
The Android Open Source Project | 9066cfe | 2009-03-03 19:31:44 -0800 | [diff] [blame] | 407 | * |
| 408 | * @see #onPostExecute |
| 409 | * @see #doInBackground |
| 410 | */ |
Tor Norbye | 83c6896 | 2015-03-10 20:55:31 -0700 | [diff] [blame] | 411 | @MainThread |
The Android Open Source Project | 9066cfe | 2009-03-03 19:31:44 -0800 | [diff] [blame] | 412 | protected void onPreExecute() { |
| 413 | } |
| 414 | |
| 415 | /** |
Romain Guy | 0bbd8d8 | 2011-10-11 18:13:37 -0700 | [diff] [blame] | 416 | * <p>Runs on the UI thread after {@link #doInBackground}. The |
Romain Guy | e95003e | 2011-01-09 13:53:06 -0800 | [diff] [blame] | 417 | * specified result is the value returned by {@link #doInBackground}.</p> |
| 418 | * |
| 419 | * <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] | 420 | * |
| 421 | * @param result The result of the operation computed by {@link #doInBackground}. |
| 422 | * |
| 423 | * @see #onPreExecute |
| 424 | * @see #doInBackground |
Romain Guy | 5ba812b | 2011-01-10 13:33:12 -0800 | [diff] [blame] | 425 | * @see #onCancelled(Object) |
The Android Open Source Project | 9066cfe | 2009-03-03 19:31:44 -0800 | [diff] [blame] | 426 | */ |
| 427 | @SuppressWarnings({"UnusedDeclaration"}) |
Tor Norbye | 83c6896 | 2015-03-10 20:55:31 -0700 | [diff] [blame] | 428 | @MainThread |
The Android Open Source Project | 9066cfe | 2009-03-03 19:31:44 -0800 | [diff] [blame] | 429 | protected void onPostExecute(Result result) { |
| 430 | } |
| 431 | |
| 432 | /** |
Romain Guy | 0bbd8d8 | 2011-10-11 18:13:37 -0700 | [diff] [blame] | 433 | * Runs on the UI thread after {@link #publishProgress} is invoked. |
The Android Open Source Project | 9066cfe | 2009-03-03 19:31:44 -0800 | [diff] [blame] | 434 | * The specified values are the values passed to {@link #publishProgress}. |
| 435 | * |
| 436 | * @param values The values indicating progress. |
| 437 | * |
| 438 | * @see #publishProgress |
| 439 | * @see #doInBackground |
| 440 | */ |
| 441 | @SuppressWarnings({"UnusedDeclaration"}) |
Tor Norbye | 83c6896 | 2015-03-10 20:55:31 -0700 | [diff] [blame] | 442 | @MainThread |
The Android Open Source Project | 9066cfe | 2009-03-03 19:31:44 -0800 | [diff] [blame] | 443 | protected void onProgressUpdate(Progress... values) { |
| 444 | } |
| 445 | |
| 446 | /** |
Romain Guy | 0bbd8d8 | 2011-10-11 18:13:37 -0700 | [diff] [blame] | 447 | * <p>Runs on the UI thread after {@link #cancel(boolean)} is invoked and |
Romain Guy | 5ba812b | 2011-01-10 13:33:12 -0800 | [diff] [blame] | 448 | * {@link #doInBackground(Object[])} has finished.</p> |
| 449 | * |
| 450 | * <p>The default implementation simply invokes {@link #onCancelled()} and |
| 451 | * ignores the result. If you write your own implementation, do not call |
| 452 | * <code>super.onCancelled(result)</code>.</p> |
The Android Open Source Project | 9066cfe | 2009-03-03 19:31:44 -0800 | [diff] [blame] | 453 | * |
Romain Guy | 5ba812b | 2011-01-10 13:33:12 -0800 | [diff] [blame] | 454 | * @param result The result, if any, computed in |
| 455 | * {@link #doInBackground(Object[])}, can be null |
| 456 | * |
| 457 | * @see #cancel(boolean) |
| 458 | * @see #isCancelled() |
| 459 | */ |
| 460 | @SuppressWarnings({"UnusedParameters"}) |
Tor Norbye | 83c6896 | 2015-03-10 20:55:31 -0700 | [diff] [blame] | 461 | @MainThread |
Romain Guy | 5ba812b | 2011-01-10 13:33:12 -0800 | [diff] [blame] | 462 | protected void onCancelled(Result result) { |
| 463 | onCancelled(); |
| 464 | } |
| 465 | |
| 466 | /** |
| 467 | * <p>Applications should preferably override {@link #onCancelled(Object)}. |
| 468 | * This method is invoked by the default implementation of |
| 469 | * {@link #onCancelled(Object)}.</p> |
| 470 | * |
Romain Guy | 0bbd8d8 | 2011-10-11 18:13:37 -0700 | [diff] [blame] | 471 | * <p>Runs on the UI thread after {@link #cancel(boolean)} is invoked and |
Romain Guy | 5ba812b | 2011-01-10 13:33:12 -0800 | [diff] [blame] | 472 | * {@link #doInBackground(Object[])} has finished.</p> |
| 473 | * |
| 474 | * @see #onCancelled(Object) |
The Android Open Source Project | 9066cfe | 2009-03-03 19:31:44 -0800 | [diff] [blame] | 475 | * @see #cancel(boolean) |
| 476 | * @see #isCancelled() |
| 477 | */ |
Tor Norbye | 83c6896 | 2015-03-10 20:55:31 -0700 | [diff] [blame] | 478 | @MainThread |
The Android Open Source Project | 9066cfe | 2009-03-03 19:31:44 -0800 | [diff] [blame] | 479 | protected void onCancelled() { |
| 480 | } |
| 481 | |
| 482 | /** |
| 483 | * Returns <tt>true</tt> if this task was cancelled before it completed |
Romain Guy | e95003e | 2011-01-09 13:53:06 -0800 | [diff] [blame] | 484 | * normally. If you are calling {@link #cancel(boolean)} on the task, |
| 485 | * the value returned by this method should be checked periodically from |
| 486 | * {@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] | 487 | * |
| 488 | * @return <tt>true</tt> if task was cancelled before it completed |
| 489 | * |
| 490 | * @see #cancel(boolean) |
| 491 | */ |
| 492 | public final boolean isCancelled() { |
Romain Guy | 657f513 | 2011-12-05 14:49:33 -0800 | [diff] [blame] | 493 | return mCancelled.get(); |
The Android Open Source Project | 9066cfe | 2009-03-03 19:31:44 -0800 | [diff] [blame] | 494 | } |
| 495 | |
| 496 | /** |
Romain Guy | e95003e | 2011-01-09 13:53:06 -0800 | [diff] [blame] | 497 | * <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] | 498 | * fail if the task has already completed, already been cancelled, |
| 499 | * or could not be cancelled for some other reason. If successful, |
| 500 | * and this task has not started when <tt>cancel</tt> is called, |
Romain Guy | e95003e | 2011-01-09 13:53:06 -0800 | [diff] [blame] | 501 | * 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] | 502 | * then the <tt>mayInterruptIfRunning</tt> parameter determines |
| 503 | * whether the thread executing this task should be interrupted in |
Romain Guy | e95003e | 2011-01-09 13:53:06 -0800 | [diff] [blame] | 504 | * an attempt to stop the task.</p> |
| 505 | * |
Romain Guy | 5ba812b | 2011-01-10 13:33:12 -0800 | [diff] [blame] | 506 | * <p>Calling this method will result in {@link #onCancelled(Object)} being |
Romain Guy | 0bbd8d8 | 2011-10-11 18:13:37 -0700 | [diff] [blame] | 507 | * invoked on the UI thread after {@link #doInBackground(Object[])} |
Romain Guy | e95003e | 2011-01-09 13:53:06 -0800 | [diff] [blame] | 508 | * returns. Calling this method guarantees that {@link #onPostExecute(Object)} |
| 509 | * is never invoked. After invoking this method, you should check the |
| 510 | * value returned by {@link #isCancelled()} periodically from |
| 511 | * {@link #doInBackground(Object[])} to finish the task as early as |
| 512 | * possible.</p> |
The Android Open Source Project | 9066cfe | 2009-03-03 19:31:44 -0800 | [diff] [blame] | 513 | * |
| 514 | * @param mayInterruptIfRunning <tt>true</tt> if the thread executing this |
| 515 | * task should be interrupted; otherwise, in-progress tasks are allowed |
| 516 | * to complete. |
| 517 | * |
| 518 | * @return <tt>false</tt> if the task could not be cancelled, |
| 519 | * typically because it has already completed normally; |
| 520 | * <tt>true</tt> otherwise |
| 521 | * |
| 522 | * @see #isCancelled() |
Romain Guy | 5ba812b | 2011-01-10 13:33:12 -0800 | [diff] [blame] | 523 | * @see #onCancelled(Object) |
The Android Open Source Project | 9066cfe | 2009-03-03 19:31:44 -0800 | [diff] [blame] | 524 | */ |
| 525 | public final boolean cancel(boolean mayInterruptIfRunning) { |
Romain Guy | 657f513 | 2011-12-05 14:49:33 -0800 | [diff] [blame] | 526 | mCancelled.set(true); |
The Android Open Source Project | 9066cfe | 2009-03-03 19:31:44 -0800 | [diff] [blame] | 527 | return mFuture.cancel(mayInterruptIfRunning); |
| 528 | } |
| 529 | |
| 530 | /** |
| 531 | * Waits if necessary for the computation to complete, and then |
| 532 | * retrieves its result. |
| 533 | * |
| 534 | * @return The computed result. |
| 535 | * |
| 536 | * @throws CancellationException If the computation was cancelled. |
| 537 | * @throws ExecutionException If the computation threw an exception. |
| 538 | * @throws InterruptedException If the current thread was interrupted |
| 539 | * while waiting. |
| 540 | */ |
| 541 | public final Result get() throws InterruptedException, ExecutionException { |
| 542 | return mFuture.get(); |
| 543 | } |
| 544 | |
| 545 | /** |
| 546 | * Waits if necessary for at most the given time for the computation |
| 547 | * to complete, and then retrieves its result. |
| 548 | * |
| 549 | * @param timeout Time to wait before cancelling the operation. |
| 550 | * @param unit The time unit for the timeout. |
| 551 | * |
| 552 | * @return The computed result. |
| 553 | * |
| 554 | * @throws CancellationException If the computation was cancelled. |
| 555 | * @throws ExecutionException If the computation threw an exception. |
| 556 | * @throws InterruptedException If the current thread was interrupted |
| 557 | * while waiting. |
| 558 | * @throws TimeoutException If the wait timed out. |
| 559 | */ |
| 560 | public final Result get(long timeout, TimeUnit unit) throws InterruptedException, |
| 561 | ExecutionException, TimeoutException { |
| 562 | return mFuture.get(timeout, unit); |
| 563 | } |
| 564 | |
| 565 | /** |
| 566 | * Executes the task with the specified parameters. The task returns |
Dianne Hackborn | 96438cd | 2011-01-25 21:42:37 -0800 | [diff] [blame] | 567 | * itself (this) so that the caller can keep a reference to it. |
| 568 | * |
| 569 | * <p>Note: this function schedules the task on a queue for a single background |
| 570 | * thread or pool of threads depending on the platform version. When first |
| 571 | * introduced, AsyncTasks were executed serially on a single background thread. |
| 572 | * Starting with {@link android.os.Build.VERSION_CODES#DONUT}, this was changed |
Romain Guy | 2c1b8c7 | 2012-05-21 10:43:26 -0700 | [diff] [blame] | 573 | * to a pool of threads allowing multiple tasks to operate in parallel. Starting |
| 574 | * {@link android.os.Build.VERSION_CODES#HONEYCOMB}, tasks are back to being |
| 575 | * executed on a single thread to avoid common application errors caused |
Dianne Hackborn | 96438cd | 2011-01-25 21:42:37 -0800 | [diff] [blame] | 576 | * by parallel execution. If you truly want parallel execution, you can use |
| 577 | * the {@link #executeOnExecutor} version of this method |
Romain Guy | 2c1b8c7 | 2012-05-21 10:43:26 -0700 | [diff] [blame] | 578 | * with {@link #THREAD_POOL_EXECUTOR}; however, see commentary there for warnings |
| 579 | * on its use. |
The Android Open Source Project | 9066cfe | 2009-03-03 19:31:44 -0800 | [diff] [blame] | 580 | * |
Romain Guy | 0bbd8d8 | 2011-10-11 18:13:37 -0700 | [diff] [blame] | 581 | * <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] | 582 | * |
| 583 | * @param params The parameters of the task. |
| 584 | * |
| 585 | * @return This instance of AsyncTask. |
| 586 | * |
| 587 | * @throws IllegalStateException If {@link #getStatus()} returns either |
Romain Guy | 0bbd8d8 | 2011-10-11 18:13:37 -0700 | [diff] [blame] | 588 | * {@link AsyncTask.Status#RUNNING} or {@link AsyncTask.Status#FINISHED}. |
Romain Guy | 2c1b8c7 | 2012-05-21 10:43:26 -0700 | [diff] [blame] | 589 | * |
| 590 | * @see #executeOnExecutor(java.util.concurrent.Executor, Object[]) |
| 591 | * @see #execute(Runnable) |
The Android Open Source Project | 9066cfe | 2009-03-03 19:31:44 -0800 | [diff] [blame] | 592 | */ |
Tor Norbye | 83c6896 | 2015-03-10 20:55:31 -0700 | [diff] [blame] | 593 | @MainThread |
The Android Open Source Project | 9066cfe | 2009-03-03 19:31:44 -0800 | [diff] [blame] | 594 | public final AsyncTask<Params, Progress, Result> execute(Params... params) { |
Joe Onorato | d630f10 | 2011-03-17 18:42:26 -0700 | [diff] [blame] | 595 | return executeOnExecutor(sDefaultExecutor, params); |
Joe Onorato | 81de61b | 2011-01-16 13:04:51 -0800 | [diff] [blame] | 596 | } |
| 597 | |
| 598 | /** |
| 599 | * Executes the task with the specified parameters. The task returns |
| 600 | * itself (this) so that the caller can keep a reference to it. |
Dianne Hackborn | 96438cd | 2011-01-25 21:42:37 -0800 | [diff] [blame] | 601 | * |
| 602 | * <p>This method is typically used with {@link #THREAD_POOL_EXECUTOR} to |
| 603 | * allow multiple tasks to run in parallel on a pool of threads managed by |
| 604 | * AsyncTask, however you can also use your own {@link Executor} for custom |
| 605 | * behavior. |
| 606 | * |
| 607 | * <p><em>Warning:</em> Allowing multiple tasks to run in parallel from |
| 608 | * a thread pool is generally <em>not</em> what one wants, because the order |
| 609 | * of their operation is not defined. For example, if these tasks are used |
| 610 | * to modify any state in common (such as writing a file due to a button click), |
| 611 | * there are no guarantees on the order of the modifications. |
| 612 | * Without careful work it is possible in rare cases for the newer version |
| 613 | * of the data to be over-written by an older one, leading to obscure data |
| 614 | * loss and stability issues. Such changes are best |
| 615 | * executed in serial; to guarantee such work is serialized regardless of |
| 616 | * platform version you can use this function with {@link #SERIAL_EXECUTOR}. |
Joe Onorato | 81de61b | 2011-01-16 13:04:51 -0800 | [diff] [blame] | 617 | * |
Romain Guy | 0bbd8d8 | 2011-10-11 18:13:37 -0700 | [diff] [blame] | 618 | * <p>This method must be invoked on the UI thread. |
Joe Onorato | 81de61b | 2011-01-16 13:04:51 -0800 | [diff] [blame] | 619 | * |
| 620 | * @param exec The executor to use. {@link #THREAD_POOL_EXECUTOR} is available as a |
| 621 | * convenient process-wide thread pool for tasks that are loosely coupled. |
| 622 | * @param params The parameters of the task. |
| 623 | * |
| 624 | * @return This instance of AsyncTask. |
| 625 | * |
| 626 | * @throws IllegalStateException If {@link #getStatus()} returns either |
Romain Guy | 0bbd8d8 | 2011-10-11 18:13:37 -0700 | [diff] [blame] | 627 | * {@link AsyncTask.Status#RUNNING} or {@link AsyncTask.Status#FINISHED}. |
Romain Guy | 2c1b8c7 | 2012-05-21 10:43:26 -0700 | [diff] [blame] | 628 | * |
| 629 | * @see #execute(Object[]) |
Joe Onorato | 81de61b | 2011-01-16 13:04:51 -0800 | [diff] [blame] | 630 | */ |
Tor Norbye | 83c6896 | 2015-03-10 20:55:31 -0700 | [diff] [blame] | 631 | @MainThread |
Joe Onorato | 81de61b | 2011-01-16 13:04:51 -0800 | [diff] [blame] | 632 | public final AsyncTask<Params, Progress, Result> executeOnExecutor(Executor exec, |
| 633 | Params... params) { |
The Android Open Source Project | 9066cfe | 2009-03-03 19:31:44 -0800 | [diff] [blame] | 634 | if (mStatus != Status.PENDING) { |
| 635 | switch (mStatus) { |
| 636 | case RUNNING: |
| 637 | throw new IllegalStateException("Cannot execute task:" |
| 638 | + " the task is already running."); |
| 639 | case FINISHED: |
| 640 | throw new IllegalStateException("Cannot execute task:" |
| 641 | + " the task has already been executed " |
| 642 | + "(a task can be executed only once)"); |
| 643 | } |
| 644 | } |
| 645 | |
| 646 | mStatus = Status.RUNNING; |
| 647 | |
| 648 | onPreExecute(); |
| 649 | |
| 650 | mWorker.mParams = params; |
Joe Onorato | 81de61b | 2011-01-16 13:04:51 -0800 | [diff] [blame] | 651 | exec.execute(mFuture); |
The Android Open Source Project | 9066cfe | 2009-03-03 19:31:44 -0800 | [diff] [blame] | 652 | |
| 653 | return this; |
| 654 | } |
| 655 | |
| 656 | /** |
Dianne Hackborn | 96438cd | 2011-01-25 21:42:37 -0800 | [diff] [blame] | 657 | * Convenience version of {@link #execute(Object...)} for use with |
Romain Guy | 2c1b8c7 | 2012-05-21 10:43:26 -0700 | [diff] [blame] | 658 | * a simple Runnable object. See {@link #execute(Object[])} for more |
| 659 | * information on the order of execution. |
| 660 | * |
| 661 | * @see #execute(Object[]) |
| 662 | * @see #executeOnExecutor(java.util.concurrent.Executor, Object[]) |
Joe Onorato | 81de61b | 2011-01-16 13:04:51 -0800 | [diff] [blame] | 663 | */ |
Tor Norbye | 83c6896 | 2015-03-10 20:55:31 -0700 | [diff] [blame] | 664 | @MainThread |
Joe Onorato | 81de61b | 2011-01-16 13:04:51 -0800 | [diff] [blame] | 665 | public static void execute(Runnable runnable) { |
Joe Onorato | d630f10 | 2011-03-17 18:42:26 -0700 | [diff] [blame] | 666 | sDefaultExecutor.execute(runnable); |
Joe Onorato | 81de61b | 2011-01-16 13:04:51 -0800 | [diff] [blame] | 667 | } |
| 668 | |
| 669 | /** |
The Android Open Source Project | 9066cfe | 2009-03-03 19:31:44 -0800 | [diff] [blame] | 670 | * This method can be invoked from {@link #doInBackground} to |
Romain Guy | 0bbd8d8 | 2011-10-11 18:13:37 -0700 | [diff] [blame] | 671 | * publish updates on the UI thread while the background computation is |
The Android Open Source Project | 9066cfe | 2009-03-03 19:31:44 -0800 | [diff] [blame] | 672 | * still running. Each call to this method will trigger the execution of |
Romain Guy | 0bbd8d8 | 2011-10-11 18:13:37 -0700 | [diff] [blame] | 673 | * {@link #onProgressUpdate} on the UI thread. |
Dmitri Plotnikov | bef9c7a | 2010-06-16 15:38:07 -0700 | [diff] [blame] | 674 | * |
John Spurlock | 3390018 | 2014-01-02 11:04:18 -0500 | [diff] [blame] | 675 | * {@link #onProgressUpdate} will not be called if the task has been |
Romain Guy | 4aaf8ec | 2010-06-03 10:56:41 -0700 | [diff] [blame] | 676 | * canceled. |
The Android Open Source Project | 9066cfe | 2009-03-03 19:31:44 -0800 | [diff] [blame] | 677 | * |
| 678 | * @param values The progress values to update the UI with. |
| 679 | * |
| 680 | * @see #onProgressUpdate |
| 681 | * @see #doInBackground |
| 682 | */ |
Tor Norbye | 83c6896 | 2015-03-10 20:55:31 -0700 | [diff] [blame] | 683 | @WorkerThread |
The Android Open Source Project | 9066cfe | 2009-03-03 19:31:44 -0800 | [diff] [blame] | 684 | protected final void publishProgress(Progress... values) { |
Romain Guy | 4aaf8ec | 2010-06-03 10:56:41 -0700 | [diff] [blame] | 685 | if (!isCancelled()) { |
Jeff Brown | bba231d | 2014-11-14 15:49:45 -0800 | [diff] [blame] | 686 | getHandler().obtainMessage(MESSAGE_POST_PROGRESS, |
Romain Guy | 4aaf8ec | 2010-06-03 10:56:41 -0700 | [diff] [blame] | 687 | new AsyncTaskResult<Progress>(this, values)).sendToTarget(); |
| 688 | } |
The Android Open Source Project | 9066cfe | 2009-03-03 19:31:44 -0800 | [diff] [blame] | 689 | } |
| 690 | |
| 691 | private void finish(Result result) { |
Romain Guy | e95003e | 2011-01-09 13:53:06 -0800 | [diff] [blame] | 692 | if (isCancelled()) { |
Romain Guy | 5ba812b | 2011-01-10 13:33:12 -0800 | [diff] [blame] | 693 | onCancelled(result); |
Romain Guy | e95003e | 2011-01-09 13:53:06 -0800 | [diff] [blame] | 694 | } else { |
| 695 | onPostExecute(result); |
| 696 | } |
The Android Open Source Project | 9066cfe | 2009-03-03 19:31:44 -0800 | [diff] [blame] | 697 | mStatus = Status.FINISHED; |
| 698 | } |
| 699 | |
| 700 | private static class InternalHandler extends Handler { |
Makoto Onuki | 1488a3a | 2017-05-24 12:25:46 -0700 | [diff] [blame] | 701 | public InternalHandler(Looper looper) { |
| 702 | super(looper); |
Jeff Brown | bba231d | 2014-11-14 15:49:45 -0800 | [diff] [blame] | 703 | } |
| 704 | |
The Android Open Source Project | 9066cfe | 2009-03-03 19:31:44 -0800 | [diff] [blame] | 705 | @SuppressWarnings({"unchecked", "RawUseOfParameterizedType"}) |
| 706 | @Override |
| 707 | public void handleMessage(Message msg) { |
Jeff Brown | bba231d | 2014-11-14 15:49:45 -0800 | [diff] [blame] | 708 | AsyncTaskResult<?> result = (AsyncTaskResult<?>) msg.obj; |
The Android Open Source Project | 9066cfe | 2009-03-03 19:31:44 -0800 | [diff] [blame] | 709 | switch (msg.what) { |
| 710 | case MESSAGE_POST_RESULT: |
| 711 | // There is only one result |
| 712 | result.mTask.finish(result.mData[0]); |
| 713 | break; |
| 714 | case MESSAGE_POST_PROGRESS: |
| 715 | result.mTask.onProgressUpdate(result.mData); |
| 716 | break; |
The Android Open Source Project | 9066cfe | 2009-03-03 19:31:44 -0800 | [diff] [blame] | 717 | } |
| 718 | } |
| 719 | } |
| 720 | |
| 721 | private static abstract class WorkerRunnable<Params, Result> implements Callable<Result> { |
| 722 | Params[] mParams; |
| 723 | } |
| 724 | |
| 725 | @SuppressWarnings({"RawUseOfParameterizedType"}) |
| 726 | private static class AsyncTaskResult<Data> { |
| 727 | final AsyncTask mTask; |
| 728 | final Data[] mData; |
| 729 | |
| 730 | AsyncTaskResult(AsyncTask task, Data... data) { |
| 731 | mTask = task; |
| 732 | mData = data; |
| 733 | } |
| 734 | } |
| 735 | } |