以下是链接:
转:
1 package com.wyl.myasyctask; 2 3 import java.io.InputStream; 4 5 import android.app.Activity; 6 import android.app.ProgressDialog; 7 import android.content.Context; 8 import android.graphics.Bitmap; 9 import android.graphics.BitmapFactory; 10 import android.os.AsyncTask; 11 import android.os.Bundle; 12 import android.util.Log; 13 import android.view.View; 14 import android.widget.Button; 15 import android.widget.ImageView; 16 17 public class MainActivity extends Activity { 18 private static final String sImageUrl = "http://fashion.qqread.com/ArtImage/20110225/0083_13.jpg"; 19 private Button mLoadButton; 20 private ImageView mImageView; 21 22 @Override 23 protected void onCreate(Bundle savedInstanceState) { 24 super.onCreate(savedInstanceState); 25 setContentView(R.layout.main); 26 27 Log.i("UI thread", " >> onCreate()"); 28 29 mImageView = (ImageView) this.findViewById(R.id.ImageVivew); 30 31 mLoadButton = (Button) this.findViewById(R.id.LoadButton); 32 mLoadButton.setOnClickListener(new View.OnClickListener() { 33 @Override 34 public void onClick(View v) { 35 LoadImageTask task = new LoadImageTask(v.getContext()); 36 task.execute(sImageUrl);// 源码中得知,会调用onPreExecute()...方法 37 } 38 }); 39 40 } 41 42 class LoadImageTask extends AsyncTask{ 43 private ProgressDialog mProgressBar; 44 45 LoadImageTask(Context context) { 46 mProgressBar = new ProgressDialog(context); 47 mProgressBar.setCancelable(true); 48 mProgressBar.setMessage("setMessage()..."); 49 mProgressBar.setProgressStyle(ProgressDialog.STYLE_SPINNER); 50 mProgressBar.setMax(100); 51 } 52 53 @Override 54 protected Bitmap doInBackground(String... params) { 55 System.out.println("doInBackground()..."); 56 57 Bitmap bitmap = null; 58 59 try { 60 publishProgress(10); 61 Thread.sleep(1000); 62 63 InputStream in = new java.net.URL(sImageUrl).openStream(); 64 publishProgress(60); 65 Thread.sleep(1000); 66 67 bitmap = BitmapFactory.decodeStream(in); 68 in.close(); 69 } catch (Exception e) { 70 e.printStackTrace(); 71 } 72 73 publishProgress(100); 74 return bitmap; 75 } 76 77 @Override 78 protected void onCancelled() { 79 super.onCancelled(); 80 } 81 82 @Override 83 protected void onPreExecute() { 84 85 mProgressBar.setProgress(0); 86 mProgressBar.setMessage("Image downloading ... 0%"); 87 mProgressBar.show(); 88 System.out.println("onPreExecute()..."); 89 } 90 91 @Override 92 protected void onPostExecute(Bitmap result) { 93 System.out.println("onPostExecute()..."); 94 if (result != null) { 95 mProgressBar.setMessage("Image downloading success!"); 96 mImageView.setImageBitmap(result); 97 } else { 98 mProgressBar.setMessage("Image downloading failure!"); 99 }100 101 mProgressBar.dismiss();102 }103 104 @Override105 protected void onProgressUpdate(Integer... values) {106 System.out.println("onProgressUpdate()...");107 mProgressBar.setMessage("Image downloading ... %" + values[0]);108 mProgressBar.setProgress(values[0]);109 }110 }111 112 }
main.xml:
1 27 8 14 15 21 22 23