Learning notes for Android-AsyncTask
(1) This file is mainly used to demonstrate how to download images from Asynchronous tasks.
(2) The layout code is as follows: An ImageView is used to store the downloaded image, and a Button is used to start asynchronous task download.
(3) Control
Package com. example. asynctask_download; import java. io. IOException; import org. apache. http. httpResponse; import org. apache. http. client. clientProtocolException; import org. apache. http. client. httpClient; import org. apache. http. client. methods. httpGet; import org. apache. http. impl. client. defaultHttpClient; import org. apache. http. util. entityUtils; import android. app. activity; import android. app. progressDialog; imp Ort android. graphics. bitmap; import android. graphics. bitmapFactory; import android. OS. asyncTask; import android. OS. bundle; import android. view. menu; import android. view. view; import android. view. view. onClickListener; import android. widget. button; import android. widget. imageView; public class MainActivity extends Activity {private Button button1; private ImageView imageView1; private final String IMAGE_PATH = "Http://www.baidu.com/img/bd_logo1.png"; // set the URL of the webpage image private ProgressDialog progredialog; @ Overrideprotected void onCreate (Bundle savedInstanceState) {super. onCreate (savedInstanceState); setContentView (R. layout. activity_main); button1 = (Button) this. findViewById (R. id. button1); imageView1 = (ImageView) this. findViewById (R. id. imageView1);/** download progress bar setting */progressDialog = new ProgressDialog (this); progr EssDialog. setTitle ("prompt"); progressDialog. setCancelable (false); progressDialog. setMessage ("the image is being downloaded. Please wait! "); Button1.setOnClickListener (new OnClickListener () {@ Overridepublic void onClick (View v) {/** asynchronous task, execute download image */new mytask(cmd.exe cute (IMAGE_PATH) ;}};}/** asynchronous task: three parameters, four steps onPreExecute (), * doInBackground (), onProgressUpdate (), onPostExecute (), void */public class MyTask extends AsyncTask can be used when no parameter is passed in
{/** OnPreExecute () method runs on the UI thread before the background operation starts */@ Overrideprotected void onPreExecute () {super. onPreExecute (); progressDialog. show ();}/** the doInBackground method runs in the background and processes background operations */@ Overrideprotected byte [] doInBackground (String... params) {HttpClient httpClient = new DefaultHttpClient (); HttpGet httpGet = new HttpGet (params [0]); byte [] result = null; try {HttpResponse httpResponse = httpClient.exe cute (httpGet); if (httpResponse. getStatusLine (). getStatusCode () = 200) {result = EntityUtils. toByteArray (httpResponse. getEntity () ;}} catch (ClientProtocolException e) {e. printStackTrace ();} catch (IOException e) {e. printStackTrace ();} finally {httpClient. getConnectionManager (). shutdown ();} return result ;}@ Overrideprotected void onProgressUpdate (Integer... values) {super. onProgressUpdate (values);}/** the onPostExecute () method runs in the UI thread */@ Overrideprotected void onPostExecute (byte [] result) {super. onPostExecute (result);/** place the downloaded bitmap in imagView * result is the downloaded image */Bitmap bitmap = BitmapFactory. decodeByteArray (result, 0, result. length); imageView1.setImageBitmap (bitmap); progressDialog. dismiss () ;}@ Overridepublic boolean onCreateOptionsMenu (Menu menu) {getMenuInflater (). inflate (R. menu. main, menu); return true ;}}
Result:
(5) display download of files with a scale bar: <喎?http: www.bkjia.com kf ware vc " target="_blank" class="keylink"> VcD4KPHA + PC9wPgo8cHJlIGNsYXNzPQ = "brush: java;"> package com. example. asynctask_download; import java. io. byteArrayOutputStream; import java. io. IOException; import java. io. inputStream; import org. apache. http. httpResponse; import org. apache. http. client. clientProtocolException; import org. apache. http. client. httpClient; import org. apache. http. client. methods. httpGet; import org. apache. http. impl. client. defaultHttpC Lient; import org. apache. http. util. entityUtils; import android. r. integer; import android. app. activity; import android. app. progressDialog; import android. graphics. bitmap; import android. graphics. bitmapFactory; import android. OS. asyncTask; import android. OS. bundle; import android. view. menu; import android. view. view; import android. view. view. onClickListener; import android. widget. button; import android. widget. ima GeView; public class MainActivity extends Activity {private Button button1; private ImageView imageView1; private final String IMAGE_PATH = "http://img.daimg.com/uploads/allimg/150114/3-150114151438.jpg"; // set the address of the webpage image private ProgressDialog ssdialog; @ Overrideprotected void onCreate (Bundle savedInstanceState) {super. onCreate (savedInstanceState); setContentView (R. layout. activity_main); button1 = (Ton) this. findViewById (R. id. button1); imageView1 = (ImageView) this. findViewById (R. id. imageView1);/** download progress bar setting */progressDialog = new ProgressDialog (this); progressDialog. setTitle ("prompt"); progressDialog. setCancelable (false); progressDialog. setMessage ("the image is being downloaded. Please wait! "); ProgressDialog. setProgressStyle (ProgressDialog. STYLE_HORIZONTAL); button1.setOnClickListener (new OnClickListener () {@ Overridepublic void onClick (View v) {/** asynchronous task, execute download image */new mytask(cmd.exe cute (IMAGE_PATH) ;}}) ;}/ ** asynchronous task: three parameters: the first address, the second address, and the third result take four steps: onPreExecute (), * doInBackground (), onProgressUpdate (), onPostExecute () when no parameters are passed in, you can use void */public class MyTask extends AsyncTask {/** OnPreExecute () method runs on the UI thread before the background operation starts */@ Overrideprotected void onPreExecute () {super. onPreExecute (); progressDialog. show ();}/** the doInBackground method runs in the background and processes background operations */@ Overrideprotected byte [] doInBackground (String... params) {HttpClient httpClient = new DefaultHttpClient (); HttpGet httpGet = new HttpGet (params [0]); // The first parameter is the input file address byte [] result = null; inputStream inputStream = null; // file stream ByteArrayOutpu TStream outputStream = new ByteArrayOutputStream (); try {HttpResponse httpResponse = httpClient.exe cute (httpGet); long file_length = httpResponse. getEntity (). getContentLength (); // The total object length: int total_length = 0; byte [] data = new byte [1024]; int len = 0; if (httpResponse. getStatusLine (). getStatusCode () = 200) {// result = // EntityUtils. toByteArray (httpResponse. getEntity (); inputStream = httpResponse. getEnt Ity (). getContent (); while (len = inputStream. read (data ))! =-1) {total_length + = len; // generate scale, progress int progress_value = (int) (total_length/(float) file_length) * 100); publishProgress (progress_value ); // publish the scale unit outputStream. write (data, 0, len) ;}result = outputStream. toByteArray ();} catch (ClientProtocolException e) {e. printStackTrace ();} catch (IOException e) {e. printStackTrace ();} finally {httpClient. getConnectionManager (). shutdown ();} return result ;}@ Overrideprotected void onProgressUpdate (Integer... values) {super. onProgressUpdate (values); progressDialog. setProgress (values [0]);}/** once the background operation is complete, the onPostExecute () method will run in the UI thread */@ Overrideprotected void onPostExecute (byte [] result) {super. onPostExecute (result);/** place the downloaded bitmap in imagView. The result is the downloaded image */Bitmap bitmap = BitmapFactory. decodeByteArray (result, 0, result. length); imageView1.setImageBitmap (bitmap); progressDialog. dismiss () ;}@ Overridepublic boolean onCreateOptionsMenu (Menu menu) {getMenuInflater (). inflate (R. menu. main, menu); return true ;}}