Android _ practical technology (2) -- How to Use AsyncTask, androidasynctask

Source: Internet
Author: User

Android _ practical technology (2) -- How to Use AsyncTask, androidasynctask

AsyncTask is a message processing class that is easier to use than Handler. It is necessary to master it. Let's look at it directly!

Bytes -----------------------------------------------------------------------------------------------------------------

AsyncTask is an abstract class (public abstract class AsyncTask extends Object). To use it, we must create a subclass to inherit it.

Take a look at this abstract class: android. OS. AsyncTask <Params, Progress, Result>. Three generic parameters are specified. Let's analyze these three parameters first:

1. Params: The parameter that needs to be passed in when AsyncTask is executed. It can be used in background tasks. Why not? OK. The following code will show you how to use it.

New downloadtask(cmd.exe cute (params) --> doInBackground (Integer... params) // you can customize the Integer here.

2. Progress: When a background task is executed, if you need to display the current Progress on the interface, use the generic type specified hereProgress Unit.

3. Result: After the task is executed, if you need to return the Result, use the generic type specified hereReturn Value TypeFor example, Boolean or String type is often used as the return type.

 Notice:These three parameters are generic parameters, that is, the parameter type is passed in as required. Therefore, you must clearly set and use the parameter type during the use of methods.

Here is the simplest way to customize AsyncTask:

Class DownloadTask extends AsyncTask <Void, Integer, Boolean> {

......

}

Of course, after defining a subclass that inherits AsyncTask, we also need to override several methods of AsyncTask:

1. onPreExecute ()

2. doInBackground (Params ...)

3. onProgressUpdate (Progress ...)

4. onPostExecute (Result)

The following describes the procedure of using these four methods in detail:

OnPreExecute (): As the name suggests, this method is the operation that needs to be executed before the asynchronous task is processed. So what does it operate? In short, some initialization operations are performed on the interface, such as displaying a progress bar dialog box. This method is not our key method, but it can be cleverly used in the process to enhance the interface's accessibility.

Protected void onPreExecute () {super. onPreExecute (); // some preprocessing can be performed}

DoInBackground (Params...): This is in AsyncTask.Most importantBecause all the code in this method will run in the Child thread, we also process all the time-consuming tasks in this method.

View the Code directly:

Protected Boolean doInBackground (Integer... params) {// params is passed in by execute (). The execute method can find the answer below for (int I = 0; I <101; I ++) {publishProgress (I); // update the UI of the main thread. The onProgressUpdate () method is called.
Try {Thread. sleep (params [0]); // sleep thread} catch (Exception e) {e. printStackTrace () ;}return true; // return a result after the task is completed. The result of the Boolean Type here}

Through the above code, we can find that once a task is completed, the return statement can be used to return the execution result of the task. If the third generic parameter of AsyncTask is specified as Void, the task execution result is not returned.

UI operations cannot be performed in this method (the Sub-thread cannot modify the main thread). To update the UI elements, you must callPublishProgress (Progress ...)Method.

OnProgressUpdate (Progress ...): When publishProgress (Progress...) is called in the background task ...) after the method, this method will be called soon. The parameters in this method are sent from which side. I don't want to explain it.

In this method, you can perform operations on the UI, and use the values in the parameters to update the interface elements accordingly. Why? On the code !.

Protected void onProgressUpdate (Integer... values) {// values [0] = I MainActivity. this. text. setText ("current progress:" + String. valueOf (values [0]) + "%"); // operate on the main thread}

OnPostExecute (Result): This function is used to execute some operations after return. We can understand the Code directly.

Protected void onPostExecute (Boolean B) {// B --> true if (B) {Toast. makeText (getBaseContext (), "Download succeed", Toast. LENGTH_SHORT ). show (); // subsequent operations} else {Toast. makeText (getBaseContext (), "Download failed", Toast. LENGTH_SHORT ). show ();}}

So the question is, we have defined the class and overwritten various methods at the same time, but how can we start it?

To start this task, you only need to write a line of code:New downloadtask(cmd.exe cute ();

Protected void onCreate (Bundle savedInstanceState) {// do not say you do not know this method ~ Super. onCreate (savedInstanceState); setContentView (R. layout. activity_main); new downloadtask(cmd.exe cute (100); // you can start asynchronous classes}

[Postscript]

Xiao Bian tries its best to make Android fans understand and understand it through its own understanding and meticulous templates. Of course, Xiao Bian is also a learner, I hope that we can learn and make progress together to discover and correct problems during the learning process!

 

Related Article

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.