Android-- multithread of AsyncTask

Preface

  This blog will introduce the use of AsyncTask, had introduced the thread and process. In AsyncTask, running in the user interface, performing asynchronous operations, and the execution results are published in the UI thread, and don't need to deal with thread and Handler. In this blog, will explain the basic introduction to AsyncTask, and how to use, the use will end in a simple Demo on AsyncTask.


AsyncTask

  AsyncTask, The asynchronous task, can be simple asynchronous operations, and the execution results published to the UI main thread. The AsyncTask is an abstract class, its interior is actually a combination of Thread and Handler to realize the asynchronous thread operations, but it forms a common thread frame, more clear and simple. AsyncTask should be used for relatively brief operation (up to a few seconds). If you need to keep long time running thread, you can use the ThreadPooExecutor or FutureTask, on the two types of content, then introduces, this blog mainly introduces AsyncTask.

  AsyncTask was defined as an operation, running on a background thread, and the results are published in the UI thread. Parameters of asynchronous work on its return value is specified with three parameters: Params, Progress, generic Result. AsyncTask will go through 4 steps: onPreExecute, doInBackground, onProgressUpdate, onPostExecute. The following detailed explanation of these three parameters and four steps:

  Three generic parameters:

  An asynchronous task will experience four stages:

  Schematic diagram of four steps described above.:

AsyncTask cancel task

  In any position in the program, are available through cancel (Boolean) method to cancel task, when cancel task, will change the isCancelled () returns the value, so that it returns true. After calling onCancelled (Object) method, instead of the onPostExecute () () returns the result by doInBackground. In the operation, can often through the isCancelled () method to see whether the task was cancelled.


Use the rules of AsyncTask

  The use of AsyncTask must follow the following rules:

Example

  A simple example, download a network image by AsyncTask, download time show a waiting box, and display in a ImageView.

  Realization of the code:

 1 package com.bgxt.datatimepickerdemo;
 2 
 3 import org.apache.http.HttpEntity;
 4 import org.apache.http.HttpResponse;
 5 import org.apache.http.client.HttpClient;
 6 import org.apache.http.client.methods.HttpGet;
 7 import org.apache.http.impl.client.DefaultHttpClient;
 8 import org.apache.http.util.EntityUtils;
 9 
10 import android.app.Activity;
11 import android.app.ProgressDialog;
12 import android.graphics.Bitmap;
13 import android.graphics.BitmapFactory;
14 import android.os.AsyncTask;
15 import android.os.Bundle;
16 import android.view.View;
17 import android.widget.Button;
18 import android.widget.ImageView;
19 
20 public class AsyncTaskActivity1 extends Activity {
21     private Button btnDown;
22     private ImageView ivImage;
23     private static String image_path = "http://ww4.sinaimg.cn/bmiddle/786013a5jw1e7akotp4bcj20c80i3aao.jpg";
24     private ProgressDialog dialog;
25 
26     @Override
27     protected void onCreate(Bundle savedInstanceState) {
28         // TODO Auto-generated method stub
29         super.onCreate(savedInstanceState);
30         setContentView(R.layout.asynctask_activity);
31 
32         btnDown = (Button) findViewById(R.id.btnDown);
33         ivImage = (ImageView) findViewById(R.id.ivSinaImage);
34         
35         // Declare a waiting box to prompt the user to wait
36         dialog=new ProgressDialog(this);
37         dialog.setTitle("Prompt information");
38         dialog.setMessage("Downloading, please try later...");
39         
40         btnDown.setOnClickListener(new View.OnClickListener() {
41 
42             @Override
43             public void onClick(View v) {
44                 // Perform an asynchronous task, and the pictures address in the form of parameters passed in
45                 new MyTask().execute(image_path);
46             }
47         });
48     }
49 
50     // The parameters of type String, Void said there was no progress information, Bitmap said the asynchronous task returns a bitmap
51     public class MyTask extends AsyncTask<String, Void, Bitmap> {
52         // That task execution before the operation
53         @Override
54         protected void onPreExecute() {
55             super.onPreExecute();
56             //Waiting display box
57             dialog.show();
58         }
59 
60         //Is mainly to complete time-consuming operation
61         @Override
62         protected Bitmap doInBackground(String... params) {
63             HttpClient httpClient=new DefaultHttpClient();
64             HttpGet httpGet=new HttpGet(params[0]);
65             Bitmap bitmap=null;
66             try {
67                 //To download images from the Internet
68                 HttpResponse httpResponse =httpClient.execute(httpGet);
69                 if(httpResponse.getStatusLine().getStatusCode()==200){
70                     HttpEntity httpEntity = httpResponse.getEntity();
71                     byte[] data=EntityUtils.toByteArray(httpEntity);
72                     bitmap=BitmapFactory.decodeByteArray(data, 0, data.length);                    
73                 }
74             } catch (Exception e) {
75                 e.printStackTrace();
76             }
77             return bitmap;
78         }
79         
80         //To complete the update of UI operation
81         @Override
82         protected void onPostExecute(Bitmap result) {
83             // TODO Auto-generated method stub
84             super.onPostExecute(result);
85             //Show the picture settings for ImageView
86             ivImage.setImageBitmap(result);
87             // The destruction of waiting box
88             dialog.dismiss();
89         }
90 
91     }
92 }

  Results show:

  

  The above Demo and did not use the schedule information, and then provide a complete AsyncTask Demo, also is to download a picture, and show to a ImageView, but here to add a progress dialog in the download process, used to display the download progress.

  Realization of the code:

  1 package com.bgxt.datatimepickerdemo;
  2 
  3 import java.io.ByteArrayOutputStream;
  4 import java.io.InputStream;
  5 
  6 import org.apache.http.HttpResponse;
  7 import org.apache.http.client.HttpClient;
  8 import org.apache.http.client.methods.HttpGet;
  9 import org.apache.http.impl.client.DefaultHttpClient;
 10 
 11 import android.app.Activity;
 12 import android.app.ProgressDialog;
 13 import android.graphics.Bitmap;
 14 import android.graphics.BitmapFactory;
 15 import android.os.AsyncTask;
 16 import android.os.Bundle;
 17 import android.view.View;
 18 import android.widget.Button;
 19 import android.widget.ImageView;
 20 
 21 public class AsyncTaskActivity2 extends Activity {
 22     private Button btnDown;
 23     private ImageView ivImage;
 24     private static String image_path = "http://ww4.sinaimg.cn/bmiddle/786013a5jw1e7akotp4bcj20c80i3aao.jpg";
 25     private ProgressDialog dialog;
 26 
 27     @Override
 28     protected void onCreate(Bundle savedInstanceState) {
 29         super.onCreate(savedInstanceState);
 30         setContentView(R.layout.asynctask_activity);
 31         btnDown = (Button) findViewById(R.id.btnDown);
 32         ivImage = (ImageView) findViewById(R.id.ivSinaImage);
 33 
 34         dialog = new ProgressDialog(this);
 35         dialog.setTitle("Prompt");
 36         dialog.setMessage("Downloading, please try later...");
 37         dialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
 38         dialog.setCancelable(false);
 39 
 40         btnDown.setOnClickListener(new View.OnClickListener() {
 41 
 42             @Override
 43             public void onClick(View v) {
 44                 //  Implementation of the asynchronous task
 45                 new MyTask().execute(image_path);
 46             }
 47         });
 48     }
 49 
 50     public class MyTask extends AsyncTask<String, Integer, Bitmap> {
 51         @Override
 52         protected void onPreExecute() {
 53             super.onPreExecute();
 54             dialog.show();
 55         }
 56 
 57         @Override
 58         protected void onProgressUpdate(Integer... values) {
 59             super.onProgressUpdate(values);
 60             // Setting the progress dialog metric
 61             dialog.setProgress(values[0]);
 62         }
 63 
 64         @Override
 65         protected void onPostExecute(Bitmap result) {
 66             super.onPostExecute(result);
 67             dialog.dismiss();
 68             ivImage.setImageBitmap(result);
 69         }
 70 
 71         @Override
 72         protected Bitmap doInBackground(String... params) {
 73             Bitmap bitmap = null;
 74             ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
 75             InputStream inputStream = null;
 76             try {
 77                 HttpClient httpClient = new DefaultHttpClient();
 78                 HttpGet httpGet = new HttpGet(params[0]);
 79                 HttpResponse httpResponse = httpClient.execute(httpGet);
 80                 if (httpResponse.getStatusLine().getStatusCode() == 200) {
 81                     inputStream = httpResponse.getEntity().getContent();
 82                     long file_length = httpResponse.getEntity()
 83                             .getContentLength();
 84                     int len = 0;
 85                     byte[] data = new byte[1024];
 86                     int total_length = 0;
 87                     // Read the image data in byte mode
 88                     while ((len = inputStream.read(data)) != -1) {
 89                         total_length += len;
 90                         // Calculate schedule
 91                         int values = (int) ((total_length / (float) file_length) * 100);
 92                         // Release schedule information
 93                         publishProgress(values);
 94                         outputStream.write(data, 0, len);
 95                     }
 96                     byte[] result=outputStream.toByteArray();
 97                     bitmap=BitmapFactory.decodeByteArray(result, 0, result.length);
 98                 }
 99             } catch (Exception e) {
100                 e.printStackTrace();
101             } finally {
102                 try {
103                     if (inputStream != null) {
104                         inputStream.close();
105                     }
106                 } catch (Exception e2) {
107                 }
108             }
109             return bitmap;
110         }
111     }
112 }

  Implementation effect:

  Download the source code

 

  Please support the original, respect the original, reproduced please indicate the source. Thank you.

Posted by Arlen at November 22, 2013 - 12:42 AM