package com.example.day9;import org.apache.http.HttpEntity;import org.apache.http.HttpResponse;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.Dialog;import android.app.ProgressDialog;import android.graphics.Bitmap;import android.graphics.BitmapFactory;import android.os.AsyncTask;import android.os.Bundle;import android.util.Log;import android.view.View;import android.view.View.OnClickListener;import android.widget.Button;import android.widget.ImageView;public class MainActivity extends Activity { private Button bt1; private ProgressDialog dialog; private String url="http://b.hiphotos.baidu.com/image/w%3D2048/sign=0240c37eb0119313c743f8b051000dd7/e4dde71190ef76c6f6ecf6979f16fdfaaf51674b.jpg"; private ImageView imageView; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); this.imageView=(ImageView)super.findViewById(R.id.iv); this.dialog=new ProgressDialog(this); this.dialog.setTitle("提示框"); this.dialog.setMessage("正在下载图片.."); this.bt1=(Button)super.findViewById(R.id.bt1); this.bt1.setOnClickListener(new OnClickListener() { @Override public void onClick(View arg0) { // TODO Auto-generated method stub new ImageDowload().execute(url); } }); } public class ImageDowload extends AsyncTask{ //第一个参数为任务,这里指的是下载链接 //第二个参数是进度,一般是Integer //第三个参数是执行结果返回类型,这里是图片 public Bitmap doInBackground(String... arg0) { // 耗时操作在这里执行,参数为任务类型,这里是指下载链接(String) HttpClient client=new DefaultHttpClient(); HttpGet httpGet=new HttpGet(arg0[0]); Bitmap bitmap=null; Log.i("lcw", arg0[0]); try { HttpResponse httpResponse = client.execute(httpGet); if(httpResponse.getStatusLine().getStatusCode()==200){ Log.i("www", httpResponse+""); HttpEntity entity=httpResponse.getEntity(); byte data[]=EntityUtils.toByteArray(entity); bitmap=BitmapFactory.decodeByteArray(data, 0, data.length); } } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } return bitmap; } @Override public void onPostExecute(Bitmap result) { // 最后操作,更新UI操作 super.onPostExecute(result); Log.i("11111111", "eeee"); MainActivity.this.imageView.setImageBitmap(result); dialog.dismiss(); } @Override public void onPreExecute() { // 最早操作,预处理动作 super.onPreExecute(); MainActivity.this.dialog.show(); } }}
效果图如下: