Android. OS. AsyncTask
AsyncTask allows simple and appropriate use of the UI thread. This class allows the execution of background operations, and then releases the results to the UI thread, while eliminating manual operation threads or handler.
AsyncTask is designed as a helper class for threads and Handler, and does not build a general thread framework.
AsyncTask is ideal for short-time operations (several seconds at most)
If you want the thread to be executed for a long time, we strongly recommend that you use the APIS provided below the java. util. concurrent package, such as Executor, ThreadPoolExecutor, and FutureTask.
An asynchronous task is an operation running on the background thread. Its execution result is published to the UI thread.
An asynchronous task is represented by three generic types (Params, SS, and Result) and four execution steps (onPreExecute, doInBackground, onProgressUpdate, and onPostExecute ).
Use
It must be a subclass of AsyncTask. The subclass must overwrite at least one method (doInBackground), and most of them will overwrite the second (onPostExecute) method.
This is an example:
Private class DownloadFilesTask extends AsyncTask {
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, you can easily execute the task:
New downloadfilestask(cmd.exe cute (url1, url2, url3 );
Generic parameters of AsyncTask
The three generic parameters of AsyncTask are as follows:
Params: parameters passed to asynchronous tasks
Progress: Progress of background task execution
Result: The Result of the background task execution.
Not all asynchronous tasks require these three parameters. If this parameter is not required, you can simply set it to Void, as shown below:
Private class MyTask extends AsyncTask {...}
Four steps
When an asynchronous task is executed, it goes through four steps:
OnPreExecute: called by the UI thread before the task starts. This is generally used to set tasks. For example, a progress bar is displayed on the user interface.
DoInBackground: After onPreExecute () is executed, it is immediately executed by the background thread. This step is used to execute background computing, which may take a long time, and parameters of asynchronous tasks will be passed in.
The running result of this step must be returned and passed to the last step.
OnProgressUpdate: it is called by the UI thread after publishProgress is called. The execution time cannot be estimated.
When a background task is executed, this method is used to display the progress on the user interface. For example, it can be used to display the progress bar animation or display the log in the text.
OnPostExecute: After the background task is executed, it is called by the UI thread. The execution result of the background thread is passed in as a parameter.
Cancel a task
You can call cancel (boolean) to cancel a task at any time. After this method is called, true is returned when isCancelled () is called.
After this method is called, onCancelled (Object) instead of onPostExecute (Object) will be executed after doInBackground (Object []) returns.
Make sure that a task is canceled as soon as possible. You should check the isCancelled () Return Value in the doInBackground (Object []) method as much as possible.
Thread rules
To make this class work properly, follow the following rules:
AsyncTask must be loaded in the main thread. In JELLY_BEAN (4.1), the system will automatically perform this operation.
The task instance must be created in the UI thread.
It must be executed in the UI thread call (execute)
Do not manually call onPreExecute (), onPostExecute, doInBackground, onProgressUpdate
One task is executed only once (if the second attempt is executed, an exception is thrown)
Memory visibility
AsyncTask ensures that all callback methods are synchronized. Therefore, the following operations are safe without additional synchronization.
Set the member variables in the constructor or onPreExecute and reference them in doInBackground.
Set member variables in doInBackground and reference them in onProgressUpdate and onPostExecute.
Execution sequence
During the first import, AsyncTasks executes tasks on a single background thread.
Starting from 1.6, the thread pool is used to allow concurrent execution of multiple tasks.
Starting from 3.0, the task is executed on a single thread to avoid possible errors caused by parallel execution.
If you really want to execute tasks in parallel, you can use THREAD_POOL_EXECUTOR to call the executeOnExecutor (java. util. concurrent. Executor, Object []) method.
Public final AsyncTask Execute (Params... params ){
Return executeOnExecutor (sDefaultExecutor
}
Original article:
Android. OS. AsyncTask
AsyncTask enables proper and easy use of the UI thread. This class allows to perform background operations and publish results on the UI thread
Without having to manipulate threads and/or handlers.
AsyncTask is designed to be a helper class around Thread and Handler and does not constitute a generic threading framework.
AsyncTasks shocould 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 varous APIs provided by
Java. util. concurrent pacakge 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.
Developer Guides
For more information about using tasks and threads, read the Processes and Threads developer guide.
Usage
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 {
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(cmd.exe cute (url1, url2, url3 );
AsyncTask's generic types
The three types used by an asynchronous task are the following:
Params, the type of the parameters sent to the task upon execution.
Progress, the type of the progress units published during the background computation.
Result, the type of the result of the background computation.
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 {...}
The 4 steps
When an asynchronous task is executed, the task goes through 4 steps:
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.
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 be also use publishProgress to publish one or more units of progress. These values are published on the UI thread, in the onProgressUpdate step.
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.
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.
Cancelling a task
A task can be canceled at any time by invoking cancel (boolean). Invoking this method will cause subsequent callto 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 canceled as quickly as possible, you shoshould always check the return value of isCancelled () periodically from
DoInBackground (Object []), if possible (inside a loop for instance .)
Threading rules
There are a few threading rules that must be followed for this class to work properly:
The AsyncTask class must be loaded on the UI thread. This is done automatically as of android. OS. Build. VERSION_CODES.JELLY_BEAN.
The task instance must be created on the UI thread.
Execute must be invoked on the UI thread.
Do not call onPreExecute (), onPostExecute, doInBackground, onProgressUpdate manually.
The task can be executed only once (an exception will be thrown if a second execution is attempted .)
Memory observability
AsyncTask guarantees that all callback callare synchronized in such a way that the following operations are safe without explicit synchronizations.
Set member fields in the constructor or onPreExecute, and refer to them in doInBackground.
Set member fields in doInBackground, and refer to them in onProgressUpdate and onPostExecute.
Order of execution
When first introduced, AsyncTasks were executed serially on a single background thread.
Starting with android. OS. Build. VERSION_CODES.DONUT (1.6), this was changed to a pool of threads allowing multiple tasks to operate in parallel.
Starting with android. OS. Build. VERSION_CODES.HONEYCOMB (3.0), 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.
Public final AsyncTask Execute (Params... params ){
Return executeOnExecutor (sDefaultExecutor
}