Android: Using Asynctask

Source: Internet
Author: User

9.2.4 using Asynctask

But to make it easier for us to manipulate the UI in a sub-thread, Android also offers some other handy tools, Asynctask is one of them. With Asynctask, you can easily switch from a child thread to the main thread, even if you don't understand the asynchronous message processing mechanism at all. Of course, asynctask behind the implementation of the principle is based on asynchronous message processing mechanism, but Android helped us to do a good package.

First look at the basic usage of asynctask, because Asynctask is an abstract class, so if we want to use it, we have to create a subclass to inherit it. In inheritance we can specify three generic parameters for the Asynctask class, and these three parameters are used as follows.

1. Params

Parameters that need to be passed in when executing asynctask can be used in a background task.

2. Progress

When a background task executes, the generic type specified here is used as the progress unit if you need to display the current progress on the interface.

3. Result

When the task finishes executing, if the result needs to be returned, the generic type specified here is used as the return value type.

Therefore, one of the simplest custom asynctask can be written as follows:

Class Downloadtask extends Asynctask<void, Integer, boolean> {

......

}

Here we specify the first generic parameter of Asynctask as Void, which means that there is no need to pass parameters to the background task when executing asynctask. The second generic parameter is specified as Integer, which indicates that the integer data is used as the progress display unit. The third generic parameter, specified as Boolean, indicates that the execution result is fed back using Boolean data.

Of course, our custom downloadtask is still an empty task and cannot do any actual work, and we need to rewrite several methods in the Asynctask to complete the customization of the task. There are four ways to rewrite frequently.

1. OnPreExecute ()

This method is called before the background task begins execution, and is used for initialization of some interfaces, such as displaying a progress bar dialog box.

2. Doinbackground (Params ...)

All the code in this method will run in a sub-thread, and we should be here to handle all the time-consuming tasks. Once the task is completed, the result of the task execution can be returned by the return statement, and if Asynctask's third generic parameter specifies Void, the task execution result is not returned. Note that the UI action is not allowed in this method, and if you need to update the UI elements, such as feedback on the progress of the current task, you can call Publishprogress (Progress ...). method to complete.

3. Onprogressupdate (Progress ...)

When Publishprogress (Progress ...) is called in a background task Method, the method is called quickly, and the parameters that are carried in the method are passed in the background task. The UI can be manipulated in this method, and the interface elements can be updated accordingly using the values in the parameters.

4. OnPostExecute (Result)

This method is called quickly when the background task is completed and returned through a return statement. The returned data is passed as a parameter to this method, and the returned data can be used to perform some UI actions, such as reminding the result of the task execution, and closing the Progress Bar dialog box.

As a result, a more complete custom asynctask can be written in the following ways:

Class Downloadtask extends Asynctask<void, Integer, boolean> {

@Override

protected void OnPreExecute () {

progressdialog.show ();// Show Progress dialog box

}

@Override

Protected Boolean doinbackground (Void ... params) {

try {

while (true) {

int downloadpercent = Dodownload ();// This is a fictional approach

Publishprogress (downloadpercent);

if (downloadpercent >= 100) {

Break

}

}

} catch (Exception e) {

return false;

}

return true;

}

@Override

protected void Onprogressupdate (Integer ... values) {

// update the download progress here

Progressdialog.setmessage ("downloaded" + values[0] + "%");

}

@Override

protected void OnPostExecute (Boolean result) {

Progressdialog.dismiss ();// Close Progress dialog box

// prompt to download results here

if (result) {

Toast.maketext (Context, "Download succeeded", Toast.length_short). Show ();

} else {

Toast.maketext (Context, "Download failed", Toast.length_short). Show ();

}

}

}

In this downloadtask, we perform specific download tasks in the Doinbackground () method. The code in this method runs in a sub-thread, so it does not affect the running of the main thread. Note that a dodownload () method is invented, which is used to calculate the current download progress and return, and we assume that this method already exists. After getting the current download progress, the following should consider how to display it to the interface, because the Doinbackground () method is running in a sub-thread, there is definitely no UI operation, so we can call pub The Lishprogress () method then passes in the current download progress so that the Onprogressupdate () method will be called quickly and the UI can be manipulated here.

When the download is complete, the Doinbackground () method returns a Boolean variable so that the OnPostExecute () method is called quickly, and this method is also run in the main thread. Then we will pop up the corresponding Toast prompt based on the results of the download, thus completing the entire Downloadtask task.

In a nutshell, the trick to using Asynctask is to perform specific time-consuming tasks in the Doinbackground () method, UI operations in the Onprogressupdate () method, and some tasks in the OnPostExecute () method. Finishing work.

If you want to start this task, just write the following code:

New Downloadtask (). Execute ();

The above is the basic usage of asynctask, how, is not feeling simple and convenient a lot? We do not need to think about asynchronous message processing mechanisms, nor do we need to use a single Handler to send and receive messages, just call the Publishprogress () method to easily switch from a child thread to a UI thread.

Android: Using Asynctask

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.