Usage instance sharing of AsyncTask in Android

  • 2020-05-26 10:06:11
  • OfStack

* AsyncTask

It seems that the modified connect() method is already available, but this anonymous thread approach is flawed: 1. Threads are expensive, and if one thread is created for each task, the application is much less efficient; 2. Second, threads cannot be managed, anonymous threads are created and started after the control of the program, if there are many requests sent, then will start a lot of threads, the system will be overwhelmed. In addition, as you saw earlier, updating UI in a new thread also requires the introduction of handler, which makes the code look bloated.

To solve this problem, OPhone introduced AsyncTask in version 1.5. The feature of AsyncTask is that tasks run outside the main thread, while the callback method is executed inside the main thread, which effectively avoids the hassle of using Handler. According to the source code of AsyncTask, AsyncTask USES the java.util.concurrent framework to manage the execution of threads and tasks. The concurrent framework is a very mature and efficient framework, which has been strictly tested. This shows that the design of AsyncTask is a good solution to the problem of anonymous threads.

AsyncTask is an abstract class, and subclasses must implement the abstract method doInBackground(Params... p), in this method to perform tasks, such as connecting to the network to obtain data. You should also generally implement the onPostExecute(Result r) method, because the results that the application CARES about are returned in this method. It is important to note that AsyncTask1 must create an instance in the main thread. AsyncTask defines three generic types, Params, Progress, and Result.

* input parameters for Params to start the task execution, such as URL requested by HTTP.
* percentage of background tasks performed by Progress.
* Result background performs the final return of the task, such as String.

The execution of AsyncTask is divided into four steps, similar to TaskListener as defined earlier. Each step corresponds to a callback method. It is important to note that these methods should not be called by the application. All the developer needs to do is implement these methods. These methods are called automatically during the execution of the task.

* onPreExecute() when calling this method before the task is executed, you can display the progress dialog here.
* doInBackground (Params...). This method is executed in a background thread and usually takes a long time to complete the main work of the task. You can call publicProgress(Progress...) during execution. To update the progress of the task.
* onProgressUpdate (Progress...). This method is executed on the main thread to show the progress of the task execution.
* onPostExecute(Result) this method executes on the main thread, and the result of the task execution is returned as a parameter to this method.

PageTask extends AsyncTask to read web content in the doInBackground() method. The source code for PageTask is shown below:

//  Set up the 3 The type parameters are respectively String,Integer,String  
    class PageTask extends AsyncTask<String, Integer, String> {  

        //  Variable length input parameters, and AsyncTask.exucute() The corresponding   
        protected String doInBackground(String... params) {  
            try {  
                HttpClient client = new DefaultHttpClient();  
                // params[0]  associative url  
                HttpGet get = new HttpGet(params[0]);  
                HttpResponse response = client.execute(get);  
                HttpEntity entity = response.getEntity();  
                long length = entity.getContentLength();  
                InputStream is = entity.getContent();  
                String s = null;  
                if (is != null) {  
                    ByteArrayOutputStream baos = new ByteArrayOutputStream();  
                    byte[] buf = new byte[128];  
                    int ch = -1;  
                    int count = 0;  
                    while ((ch = != -1) {  
                        baos.write(buf, 0, ch);  
                        count += ch;  
                        if (length > 0) {  
                            //  If you know the length of the response, call publishProgress () update progress   
                            publishProgress((int) ((count / (float) length) * 100));  
                        //  To see the progress clearly in the simulator, let the thread sleep 100ms  
                    s = new String(baos.toByteArray());            }  
                //  Returns the result   
                return s;  
            } catch (Exception e) {  
            return null;  
        protected void onCancelled() {  
        protected void onPostExecute(String result) {  
            //  return HTML The content of the page   
        protected void onPreExecute() {  
            //  The task is launched and can be displayed here 1 This is a simple dialog box   
        protected void onProgressUpdate(Integer... values) {  
            //  Update progress   

Executing PageTask is simple, just call the following code. Rerun NetworkActivity to not only grab the content of the page, but also update the progress of the page in real time. The reader tries to read a larger page to see the percentage update.

PageTask task = new PageTask();  

Download example: testAsync(

Related articles: