Show
This class was deprecated in API level 30. 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 AsyncTask is designed to be a helper class around 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 Developer GuidesFor more information about using tasks and threads, read the Processes and Threads developer guide. UsageAsyncTask must be subclassed to be used. The subclass will override at least one method ( Here is an example of subclassing: private class DownloadFilesTask extends AsyncTask<URL, Integer, Long> { protected Long doInBackground(URL... urls) { int count = urls.length; long totalSize = 0; for (int i = 0; i < 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); AsyncTask's generic typesThe three types used by an asynchronous task are the following:
Not all types are always used by an asynchronous task. To mark a type as unused, simply use the type private class MyTask extends AsyncTask<Void, Void, Void> { ... } The 4 stepsWhen an asynchronous task is executed, the task goes through 4 steps:
Cancelling a taskA task can be cancelled at any time by invoking Threading rulesThere are a few threading rules that must be followed for this class to work properly:
Memory observabilityAsyncTask guarantees that all callback calls are synchronized to ensure the following without explicit synchronizations.
Order of executionWhen first introduced, AsyncTasks were executed serially on a single background thread. Starting with If you truly want parallel execution, you can invoke Summary
FieldsSERIAL_EXECUTOR Added in API level 11 public static final Executor SERIAL_EXECUTOR
This field was deprecated in API level 30. An THREAD_POOL_EXECUTOR Added in
API level 11 public static final Executor THREAD_POOL_EXECUTOR This field was deprecated in API level 30. An Public constructorsAsyncTaskAdded in API level 3 public AsyncTask () Creates a new asynchronous task. This constructor must be invoked on the UI thread. Public methodscancel Added in
API level 3 public final boolean cancel (boolean mayInterruptIfRunning) Attempts to cancel execution of this task. This attempt will fail if the task has already completed, already been cancelled, or could not be cancelled for some other reason. If successful, and this task has not started when cancel is called, this task should never run. If the task has already started, then the mayInterruptIfRunning parameter determines whether the thread executing this task should be interrupted in an attempt to stop the task. Calling this method will result in This only requests cancellation. It never waits for a running background task to terminate, even if mayInterruptIfRunning is true.
See also:
execute Added in API level 3 public final AsyncTask<Params, Progress, Result> execute (Params... params) Executes the task with the specified parameters. The task returns itself (this) so that the caller can keep a reference to it. Note: this function schedules the task on a queue for a single background thread or pool of threads depending on the platform version. When first introduced, AsyncTasks were executed serially on a single background thread. Starting with This method must be invoked on the UI thread.
See also:
execute Added in API level 11 public static void execute (Runnable runnable) Convenience version of
See also:
executeOnExecutor Added in API level 11 public final AsyncTask<Params, Progress, Result> executeOnExecutor (Executor exec, Params... params) Executes the task with the specified parameters. The task returns itself (this) so that the caller can keep a reference to it. This method is typically used with Warning:
Allowing multiple tasks to run in parallel from a thread pool is generally not what one wants, because the order of their operation is not defined. For example, if these tasks are used to modify any state in common (such as writing a file due to a button click), there are no guarantees on the order of the modifications. Without careful work it is possible in rare cases for the newer version of the data to be over-written by an older one, leading to obscure data loss and stability
issues. Such changes are best executed in serial; to guarantee such work is serialized regardless of platform version you can use this function with This method must be invoked on the UI thread.
See also:
get Added in API level 3 public final Result get (long timeout, TimeUnit unit) Waits if necessary for at most the given time for the computation to complete, and then retrieves its result.
get Added in API level 3 public final Result get () Waits if necessary for the computation to complete, and then retrieves its result.
getStatus Added in API level 3 public final AsyncTask.Status getStatus () Returns the current status of this task.
isCancelled Added in API level 3 public final boolean isCancelled () Returns true if this task was cancelled before it
completed normally. If you are calling
See also:
Protected methodsdoInBackground Added in API level 3 protected abstract Result doInBackground (Params... params) Override this method to perform a computation on a background thread. The specified parameters are the parameters passed to
See also:
onCancelled Added in API level 3 protected void onCancelled () Applications should preferably override Runs on the UI thread after This method must be called from the main thread of your app. See also:
onCancelled Added in API level 11 protected void onCancelled (Result result) Runs on the UI thread after The default implementation simply invokes This method must be called from the main thread of your app.
See also:
onPostExecute Added in API level 3 protected void onPostExecute (Result result) Runs on the UI thread after This method won't be invoked if the task was cancelled. This method must be called from the main thread of your app.
See also:
onPreExecute Added in API level 3 protected void onPreExecute () Runs on the UI thread before See also:
onProgressUpdate Added in API level 3 protected void onProgressUpdate (Progress... values) Runs on the UI thread after
See also:
publishProgress Added in API level 3 protected final void publishProgress (Progress... values) This method can be invoked from
See also:
Content and code samples on this page are subject to the licenses described in the Content License. Java and OpenJDK are trademarks or registered trademarks of Oracle and/or its affiliates. Last updated 2022-02-10 UTC. [{ "type": "thumb-down", "id": "missingTheInformationINeed", "label":"Missing the information I need" },{ "type": "thumb-down", "id": "tooComplicatedTooManySteps", "label":"Too complicated / too many steps" },{ "type": "thumb-down", "id": "outOfDate", "label":"Out of date" },{ "type": "thumb-down", "id": "samplesCodeIssue", "label":"Samples / code issue" },{ "type": "thumb-down", "id": "otherDown", "label":"Other" }] [{ "type": "thumb-up", "id": "easyToUnderstand", "label":"Easy to understand" },{ "type": "thumb-up", "id": "solvedMyProblem", "label":"Solved my problem" },{ "type": "thumb-up", "id": "otherUp", "label":"Other" }] Which of the following technologies was the first to lead audiences to expect more control over their television watching experience quizlet?In the U.S., DBS is dominated by two companies: DirecTV and Dish Network. It is a multichannel service. Which of the following technologies was the first to lead audiences to expect more control over their television-watching experience? interactive cable.
What is the broadcast industry term for syndicated content that originally aired on a network multiple choice question?Three common types of syndication are: first-run syndication, which is programming that is broadcast for the first time as a syndicated show and is made specifically to sell directly into syndication; off-network syndication (colloquially called a "rerun"), which is the licensing of a program whose first airing was on ...
Which of the following was the first premium cable channel?HBO was the first true premium cable (or "pay-cable") network as well as the first television network intended for cable distribution on a regional or national basis; however, there were notable precursors to premium cable in the pay-television industry that operated during the 1950s and 1960s (with a few systems ...
Which law passed in 1967 United educational stations into one network?The Public Broadcasting Act of 1967 (Act) established the Corporation for Public Broadcasting (CPB), a nonprofit corporation, to disburse federal funds to noncommercial television and radio stations in support of station operations and educational programming.
|