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