Compartilhar via


AsyncTask Class

Definition

AsyncTask was intended to enable proper and easy use of the UI thread.

[Android.Runtime.Register("android/os/AsyncTask", DoNotGenerateAcw=true)]
[Java.Interop.JavaTypeParameters(new System.String[] { "Params", "Progress", "Result" })]
public abstract class AsyncTask : Java.Lang.Object
[<Android.Runtime.Register("android/os/AsyncTask", DoNotGenerateAcw=true)>]
[<Java.Interop.JavaTypeParameters(new System.String[] { "Params", "Progress", "Result" })>]
type AsyncTask = class
    inherit Object
Inheritance
AsyncTask
Derived
Attributes

Remarks

AsyncTask was intended to enable proper and easy use of the UI thread. However, the most common use case was for integrating into UI, and that would cause Context leaks, missed callbacks, or crashes on configuration changes. It also has inconsistent behavior on different versions of the platform, swallows exceptions from doInBackground, and does not provide much utility over using Executors directly.

AsyncTask is designed to be a helper class around Thread and Handler and does not constitute a generic threading framework. AsyncTasks should ideally be used for short operations (a few seconds at the most.) If you need to keep threads running for long periods of time, it is highly recommended you use the various APIs provided by the java.util.concurrent package such as Executor, ThreadPoolExecutor and FutureTask.

An asynchronous task is defined by a computation that runs on a background thread and whose result is published on the UI thread. An asynchronous task is defined by 3 generic types, called Params, Progress and Result, and 4 steps, called onPreExecute, doInBackground, onProgressUpdate and onPostExecute.

<div class="special reference"> <h3>Developer Guides</h3>

For more information about using tasks and threads, read the Processes and Threads developer guide.

</div>

<h2>Usage</h2>

AsyncTask must be subclassed to be used. The subclass will override at least one method (#doInBackground), and most often will override a second one (#onPostExecute.)

Here is an example of subclassing:

private class DownloadFilesTask extends AsyncTask&lt;URL, Integer, Long&gt; {
                protected Long doInBackground(URL... urls) {
                    int count = urls.length;
                    long totalSize = 0;
                    for (int i = 0; i &lt; count; i++) {
                        totalSize += Downloader.downloadFile(urls[i]);
                        publishProgress((int) ((i / (float) count) * 100));
                        // Escape early if cancel() is called
                        if (isCancelled()) break;
                    }
                    return totalSize;
                }

                protected void onProgressUpdate(Integer... progress) {
                    setProgressPercent(progress[0]);
                }

                protected void onPostExecute(Long result) {
                    showDialog("Downloaded " + result + " bytes");
                }
            }

Once created, a task is executed very simply:

new DownloadFilesTask().execute(url1, url2, url3);

<h2>AsyncTask's generic types</h2>

The three types used by an asynchronous task are the following:

<ol> <li>Params, the type of the parameters sent to the task upon execution.</li> <li>Progress, the type of the progress units published during the background computation.</li> <li>Result, the type of the result of the background computation.</li> </ol>

Not all types are always used by an asynchronous task. To mark a type as unused, simply use the type Void:

private class MyTask extends AsyncTask&lt;Void, Void, Void&gt; { ... }

<h2>The 4 steps</h2>

When an asynchronous task is executed, the task goes through 4 steps:

<ol> <li>#onPreExecute(), invoked on the UI thread before the task is executed. This step is normally used to setup the task, for instance by showing a progress bar in the user interface.</li> <li>#doInBackground, invoked on the background thread immediately after #onPreExecute() finishes executing. This step is used to perform background computation that can take a long time. The parameters of the asynchronous task are passed to this step. The result of the computation must be returned by this step and will be passed back to the last step. This step can also use #publishProgress to publish one or more units of progress. These values are published on the UI thread, in the #onProgressUpdate step.</li> <li>#onProgressUpdate, invoked on the UI thread after a call to #publishProgress. The timing of the execution is undefined. This method is used to display any form of progress in the user interface while the background computation is still executing. For instance, it can be used to animate a progress bar or show logs in a text field.</li> <li>#onPostExecute, invoked on the UI thread after the background computation finishes. The result of the background computation is passed to this step as a parameter.</li> </ol>

<h2>Cancelling a task</h2>

A task can be cancelled at any time by invoking #cancel(boolean). Invoking this method will cause subsequent calls to #isCancelled() to return true. After invoking this method, #onCancelled(Object), instead of #onPostExecute(Object) will be invoked after #doInBackground(Object[]) returns. To ensure that a task is cancelled as quickly as possible, you should always check the return value of #isCancelled() periodically from #doInBackground(Object[]), if possible (inside a loop for instance.)

<h2>Threading rules</h2>

There are a few threading rules that must be followed for this class to work properly:

<ul> <li>The AsyncTask class must be loaded on the UI thread. This is done automatically as of android.os.Build.VERSION_CODES#JELLY_BEAN.</li> <li>The task instance must be created on the UI thread.</li> <li>#execute must be invoked on the UI thread.</li> <li>Do not call #onPreExecute(), #onPostExecute, #doInBackground, #onProgressUpdate manually.</li> <li>The task can be executed only once (an exception will be thrown if a second execution is attempted.)</li> </ul>

<h2>Memory observability</h2>

AsyncTask guarantees that all callback calls are synchronized to ensure the following without explicit synchronizations.

<ul> <li>The memory effects of #onPreExecute, and anything else executed before the call to #execute, including the construction of the AsyncTask object, are visible to #doInBackground. <li>The memory effects of #doInBackground are visible to #onPostExecute. <li>Any memory effects of #doInBackground preceding a call to #publishProgress are visible to the corresponding #onProgressUpdate call. (But #doInBackground continues to run, and care needs to be taken that later updates in #doInBackground do not interfere with an in-progress #onProgressUpdate call.) <li>Any memory effects preceding a call to #cancel are visible after a call to #isCancelled that returns true as a result, or during and after a resulting call to #onCancelled. </ul>

<h2>Order of execution</h2>

When first introduced, AsyncTasks were executed serially on a single background thread. Starting with android.os.Build.VERSION_CODES#DONUT, this was changed to a pool of threads allowing multiple tasks to operate in parallel. Starting with android.os.Build.VERSION_CODES#HONEYCOMB, tasks are executed on a single thread to avoid common application errors caused by parallel execution.

If you truly want parallel execution, you can invoke #executeOnExecutor(java.util.concurrent.Executor, Object[]) with #THREAD_POOL_EXECUTOR.

This member is deprecated. Use the standard java.util.concurrent or Kotlin concurrency utilities instead.

Java documentation for android.os.AsyncTask.

Portions of this page are modifications based on work created and shared by the Android Open Source Project and used according to terms described in the Creative Commons 2.5 Attribution License.

Constructors

AsyncTask()

Creates a new asynchronous task.

AsyncTask(IntPtr, JniHandleOwnership)

A constructor used when creating managed representations of JNI objects; called by the runtime.

Properties

Class

Returns the runtime class of this Object.

(Inherited from Object)
Handle

The handle to the underlying Android instance.

(Inherited from Object)
IsCancelled

Returns true if this task was cancelled before it completed normally.

JniIdentityHashCode (Inherited from Object)
JniPeerMembers
PeerReference (Inherited from Object)
SerialExecutor

An Executor that executes tasks one at a time in serial order.

ThreadPoolExecutor

An Executor that can be used to execute tasks in parallel.

ThresholdClass

This API supports the Mono for Android infrastructure and is not intended to be used directly from your code.

ThresholdType

This API supports the Mono for Android infrastructure and is not intended to be used directly from your code.

Methods

Cancel(Boolean)

Attempts to cancel execution of this task.

Clone()

Creates and returns a copy of this object.

(Inherited from Object)
Dispose() (Inherited from Object)
Dispose(Boolean) (Inherited from Object)
DoInBackground(Object[])

Override this method to perform a computation on a background thread.

Equals(Object)

Indicates whether some other object is "equal to" this one.

(Inherited from Object)
Execute(IRunnable)

Convenience version of #execute(Object...) for use with a simple Runnable object.

Execute(Object[])

Executes the task with the specified parameters.

ExecuteOnExecutor(IExecutor, Object[])

Executes the task with the specified parameters.

Get()

Waits if necessary for the computation to complete, and then retrieves its result.

Get(Int64, TimeUnit)

Waits if necessary for at most the given time for the computation to complete, and then retrieves its result.

GetAsync()
GetAsync(Int64, TimeUnit)
GetHashCode()

Returns a hash code value for the object.

(Inherited from Object)
GetStatus()

Returns the current status of this task.

JavaFinalize()

Called by the garbage collector on an object when garbage collection determines that there are no more references to the object.

(Inherited from Object)
Notify()

Wakes up a single thread that is waiting on this object's monitor.

(Inherited from Object)
NotifyAll()

Wakes up all threads that are waiting on this object's monitor.

(Inherited from Object)
OnCancelled()

Applications should preferably override #onCancelled(Object).

OnCancelled(Object)

Runs on the UI thread after #cancel(boolean) is invoked and #doInBackground(Object[]) has finished.

OnPostExecute(Object)

Runs on the UI thread after #doInBackground.

OnPreExecute()

Runs on the UI thread before #doInBackground.

OnProgressUpdate(Object[])

Runs on the UI thread after #publishProgress is invoked.

PublishProgress(Object[])

This method can be invoked from #doInBackground to publish updates on the UI thread while the background computation is still running.

SetHandle(IntPtr, JniHandleOwnership)

Sets the Handle property.

(Inherited from Object)
ToArray<T>() (Inherited from Object)
ToString()

Returns a string representation of the object.

(Inherited from Object)
UnregisterFromRuntime() (Inherited from Object)
Wait()

Causes the current thread to wait until it is awakened, typically by being <em>notified</em> or <em>interrupted</em>.

(Inherited from Object)
Wait(Int64, Int32)

Causes the current thread to wait until it is awakened, typically by being <em>notified</em> or <em>interrupted</em>, or until a certain amount of real time has elapsed.

(Inherited from Object)
Wait(Int64)

Causes the current thread to wait until it is awakened, typically by being <em>notified</em> or <em>interrupted</em>, or until a certain amount of real time has elapsed.

(Inherited from Object)

Explicit Interface Implementations

IJavaPeerable.Disposed() (Inherited from Object)
IJavaPeerable.DisposeUnlessReferenced() (Inherited from Object)
IJavaPeerable.Finalized() (Inherited from Object)
IJavaPeerable.JniManagedPeerState (Inherited from Object)
IJavaPeerable.SetJniIdentityHashCode(Int32) (Inherited from Object)
IJavaPeerable.SetJniManagedPeerState(JniManagedPeerStates) (Inherited from Object)
IJavaPeerable.SetPeerReference(JniObjectReference) (Inherited from Object)

Extension Methods

JavaCast<TResult>(IJavaObject)

Performs an Android runtime-checked type conversion.

JavaCast<TResult>(IJavaObject)
GetJniTypeName(IJavaPeerable)

Applies to