Android learning notes: AsyncTask implements file download tasks. androidasynctask
(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.
<RelativeLayout xmlns: android = "http://schemas.android.com/apk/res/android" xmlns: tools = "http://schemas.android.com/tools" android: layout_width = "match_parent" android: layout_height = "match_parent" android: paddingBottom = "@ dimen/activity_vertical_margin" android: paddingLeft = "@ dimen/plugin" android: paddingRight = "@ dimen/plugin" android: paddingTop = "@ dimen/plugin" tools: context = ". mainActivity "> <ImageView android: id =" @ + id/imageView1 "android: layout_width =" wrap_content "android: layout_height =" wrap_content "android: layout_alignParentLeft =" true "android: layout_alignParentTop = "true" android: layout_marginLeft = "141dp" android: layout_marginTop = "135dp"/> <Button android: id = "@ + id/button1" android: layout_width = "wrap_content" android: layout_height = "wrap_content" android: feature = "true" android: layout_alignRight = "@ + id/imageView1" android: layout_marginBottom = "80dp" android: text = "webpage download image"/> </RelativeLayout>
(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 <String, Integer, byte []> {/** 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:
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. defaultHttpClient; import org. apache. http. util. entityUtils; I Mport 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. imageView; public class MainActivity extends Activi Ty {private Button button1; private ImageView imageView1; private final String IMAGE_PATH = "http://img.daimg.com/uploads/allimg/150114/3-150114151438.jpg"; // set the URL of the webpage image private ProgressDialog ssssdialog; @ 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); 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 () you can use void */public class MyTask extends AsyncTask <String, Integer, byte []> {/** 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 ByteArrayO UtputStream 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. ge TEntity (). 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 ;}}