Android multithreading #2 -- How to Use AsyncTask to Implement Asynchronous time-consuming operations

Source: Internet
Author: User

In the previous blog, we talked about ANR exceptions and handler class exceptions. This time I will introduce you to another method for processing time-consuming operations. Asynchronous processing of time-consuming operations was a popular method at that time, so it is very important to fully master the use of such operations. As to why it becomes popular, I will introduce the advantages of using AsyncTask first.

1: advantages of using AsyncTask

When processing time-consuming operations, such as downloading, we need to start a thread. Suppose we have hundreds of threads to start. Let me give you an example. Thread startup is like a broom. Starting a broom is like a new broom. When we use it, we will discard it. When we use it again next time, we will buy a new broom. This is a waste of resources. The use of AsyncTask would like to put more than 10 broom places. Every time we use a broom, we put it back. When someone needs it next time, we will continue to use it cyclically, saving system resources. Now you know the benefits of the AsyncTask class. Saving system resources is crucial for us to build a large project.

2: Use of AsyncTask.

(1): Let me give you an example. There is a progress bar, a text, and a button to start the download. When you click the Download button, the text displays the progress of the percentage at the current progress bar, as shown in figure

650) this. width = 650; "src =" http://www.bkjia.com/uploads/allimg/131228/06310544c-0.jpg "title =" nk1_dpd@r00004tw6ylpolicyc2@e5q.jpg "/>

(2): Write an internal class to inherit AsyncTask. In fact, the first method must be implemented, and the second method is manually called. The specific code is as follows:

class MyTask extends AsyncTask<String, Integer, String>{    @Override    protected String doInString...  params) {        publishProgress(values);        return null;    }                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                   @Override    protected void onProgressUpdate(Integer... values) {        super.onProgressUpdate(values);    }                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                   @Override    protected void onPostExecute(String result) {        super.onPostExecute(result);    }                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                               }

First, this class requires three types. The first params type is the parameter type that needs to be passed in when we start the thread pool. Generally, it is passed in URL, So I define it as String type, after this type is defined, the parameter type in the doInBackgroud method is the same as that in the String type (the doInBackground method is processed in the sub-thread to be used as the thread's run method ). It will get the URL parameters we passed in. The second Progress type is that if we need to process the main thread during time-consuming operations, we can call publishProgress (values) in the doInBackground method) method to activate the second override method onProgressUpdate () method (this method is executed in the main thread, so you can operate the UI object. values is generally used as the input progress parameter. The third parameter is that when we have processed the doInBackgroud method, it will return a result of the type of the result. Here I define it as a String. At this time, the return value of the doInBackgroud method is automatically changed to the String type.

Then the third method onPostExecute will receive the result value returned by doInBackgroud.

(3): in the authentication of anonymous classes, we will start this thread pool. Because I have defined the parameter input for the startup thread pool to be of the String type, now I have passed in a String, the Code is as follows: (this parameter is currently useless to illustrate the previous problems.


new MyTask().execute("www.baidu.com");


(4): Add a progress every 100 milliseconds and call the publishProgress () method to increase the progress bar and update the text percentage progress in the main thread ), the Code is as follows:

@ Overrideprotected String doInString... params) {// progress of 100 milliseconds + 1, 100 for (int I = 0; I <100; I ++) {try {Thread. sleep (100);} catch (InterruptedException e) {e. printStackTrace () ;}// activate onProgressUpdate and pass the progress I to publishProgress (I);} return "Download complete" ;}@ Overrideprotected void onProgressUpdate (Integer... values) {super. onProgressUpdate (values); // update progress bar. setProgress (values [0]); // update percentage progress mTextView. setText (values [0] + "% ");}

(4): After the download is complete, we update the text content in the onPostExecute () method to download.

@Overrideprotected void onPostExecute(String result) {    super.onPostExecute(result);    mTextView.setText(result);}

Success. This is how to use the AsyncTask class to Implement Asynchronous time-consuming operations. I will upload the complete code of this program to my upload. If you need it, you can download it, next time, I will use ListView and AsyncTask to create a small project for downloading songs.


This article from the "android technology" blog, please be sure to keep this source http://7735447.blog.51cto.com/7725447/1275818

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.