Usage of AsyncTask in android Development

Source: Internet
Author: User

In Android, there are two asynchronous task mechanisms: Handler and AsyncTask.

In Handler mode, a new thread needs to be created for each task. After the task is completed, a message is sent to the UI thread through the Handler instance to update the interface. This method has fine control over the entire process, but it also has some disadvantages. For example, the Code is relatively bloated and it is difficult to precisely control the thread when multiple tasks are executed simultaneously. I have already introduced Handler. If you are not clear about Handler, refer to it.

To simplify the operation, Android1.5 provides the tool class android. OS. AsyncTask, which makes it easier to create asynchronous tasks. You no longer need to compile the task thread and Handler instance to complete the same task.

Let's take a look at the definition of AsyncTask:


[Java]
Public abstract class AsyncTask <Params, Progress, Result> {

Public abstract class AsyncTask <Params, Progress, Result> {
The three generic types are "input parameters for starting task execution", "Progress of background task execution", and "type of background computing result ". In a specific scenario, not all types are used. If not, you can use the java. lang. Void type instead.

Generally, the execution of an asynchronous task includes the following steps:

1. execute (Params... params) to execute an asynchronous task. We need to call this method in the code to trigger the execution of the asynchronous task.

2. onPreExecute (), which is executed immediately after execute (Params... params) is called. It is generally used to mark the UI before executing background tasks.

3. doInBackground (Params... params), which is executed immediately after onPreExecute () is completed for time-consuming operations. This method will receive input parameters and return calculation results. During execution, you can call publishProgress (Progress... values) to update the Progress information.

4. onProgressUpdate (Progress... values). When publishProgress (Progress... values) is called, this method is executed and the Progress information is directly updated to the UI component.

5. onPostExecute (Result result). When the background operation ends, this method will be called. The calculation Result will be passed as a parameter to this method, and the result will be directly displayed on the UI component.

Pay special attention to the following points:

1. the instance of the asynchronous task must be created in the UI thread.

2. The execute (Params... params) method must be called in the UI thread.

3. Do not manually call the onPreExecute (), doInBackground (Params... params), onProgressUpdate (Progress... values), onPostExecute (Result result) methods.

4. You cannot change the UI component information in doInBackground (Params... params.

5. A task instance can only be executed once. If it is executed for the second time, an exception is thrown.

In order to have a deeper understanding of this method, the following is an example.

In this example, the progress bar countdown function is implemented. The duration is 30 s. With the decrease of time, the progress bar is gradually shortened, and the remaining time in the text box is also reduced.


[Java]
Import android. OS. AsyncTask;
Import android. widget. ProgressBar;
Import android. widget. TextView;
 
Class TestAsyncTask extends AsyncTask <String, Integer, String>
{
FullscreenActivity;
TextView textView;
ProgressBar bar;
 
Public TestAsyncTask (FullscreenActivity activity, TextView textView, ProgressBar bar ){
This. activity = activity;
This. textView = textView;
This. bar = bar;
}
// After TestAsyncTask is executed by the background thread and called by the UI thread, it is generally used to initialize interface controls, such as progress bars
@ Override
Protected void onPreExecute (){
// TODO Auto-generated method stub
Super. onPreExecute ();
}
 
// After doInBackground is executed, it is called by the UI thread to update interface operations.
@ Override
Protected void onPostExecute (String result ){
// TODO Auto-generated method stub


// TextView. setText (result );
Super. onPostExecute (result );
}
 
// After PreExcute is executed, it is called by the background thread of AysncTask, and the result is returned to the UI thread.
@ Override
Protected String doInBackground (String... params ){
// TODO Auto-generated method stub
Bar. setMax (300 );
Int I = 30;
While (true)
{
PublishProgress (int) I );
If (I = 0) break;
Try {
Thread. sleep (1000 );
} Catch (InterruptedException e ){
// TODO Auto-generated catch block
E. printStackTrace ();
}
I --;

}
Return null;
}
@ Override
Protected void onProgressUpdate (Integer... values ){
// TODO Auto-generated method stub
Bar. setProgress (values [0] * 10 );
TextView. setText ("" + values [0] + "s ");

Super. onProgressUpdate (values );
}


}

Import android. OS. AsyncTask;
Import android. widget. ProgressBar;
Import android. widget. TextView;

Class TestAsyncTask extends AsyncTask <String, Integer, String>
{
FullscreenActivity;
TextView textView;
ProgressBar bar;

Public TestAsyncTask (FullscreenActivity activity, TextView textView, ProgressBar bar ){
This. activity = activity;
This. textView = textView;
This. bar = bar;
}
// After TestAsyncTask is executed by the background thread and called by the UI thread, it is generally used to initialize interface controls, such as progress bars
@ Override
Protected void onPreExecute (){
// TODO Auto-generated method stub
Super. onPreExecute ();
}

// After doInBackground is executed, it is called by the UI thread to update interface operations.
@ Override
Protected void onPostExecute (String result ){
// TODO Auto-generated method stub


// TextView. setText (result );
Super. onPostExecute (result );
}

// After PreExcute is executed, it is called by the background thread of AysncTask, and the result is returned to the UI thread.
@ Override
Protected String doInBackground (String... params ){
// TODO Auto-generated method stub
Bar. setMax (300 );
Int I = 30;
While (true)
{
PublishProgress (int) I );
If (I = 0) break;
Try {
Thread. sleep (1000 );
} Catch (InterruptedException e ){
// TODO Auto-generated catch block
E. printStackTrace ();
}
I --;

}
Return null;
}
@ Override
Protected void onProgressUpdate (Integer... values ){
// TODO Auto-generated method stub
Bar. setProgress (values [0] * 10 );
TextView. setText ("" + values [0] + "s ");

Super. onProgressUpdate (values );
}


}
In the UI thread:


[Java]
New TestAsyncTask (FullscreenActivity. this, textView, bar).exe cute ("");

New TestAsyncTask (FullscreenActivity. this, textView, bar).exe cute ("");
AsyncTask is used to Implement Asynchronous update progress bar. The front-end UI can be updated on the background without affecting the running of the program.

This method can also be used to display processing progress, timing, loading progress, and other functions.


 

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.