import java.io.IOException; import org.apache.http.HttpEntity; 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.os.AsyncTask; import android.os.Bundle; import android.app.Activity; import android.app.ProgressDialog; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.view.Menu; import android.view.View; import android.widget.Button; import android.widget.ImageView; public class MainActivity extends Activity { public Button button; public ImageView imageView; public ProgressDialog progressDialog; public String image_path = "http://www.eoeandroid.com/static/image/common/eoe_logo.png"; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); button = (Button) this.findViewById(R.id.button1); imageView = (ImageView) this.findViewById(R.id.imageView1); progressDialog = new ProgressDialog(MainActivity.this); progressDialog.setTitle("提示信息"); progressDialog.setMessage("正在下载图片,请稍后"); button.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { // 执行异步任务下载图片 new Mytask().execute(image_path); } }); } @Override public boolean onCreateOptionsMenu(Menu menu) { // Inflate the menu; this adds items to the action bar if it is present. getMenuInflater().inflate(R.menu.main, menu); return true; } // 需要先继承AsyncTask接口,第一个参数是执行路径,第二个是进度,第三个是返回值 public class Mytask extends AsyncTask<String, Void, Bitmap> { // 可以在这里执行耗时操作 protected Bitmap doInBackground(String... params) { // 实例化网络客户端对象 HttpClient httpClient = new DefaultHttpClient(); // 实例化请求对象,并且取出参数列表中的参数 HttpGet httpGet = new HttpGet(params[0]); Bitmap bitmap = null; try { // 发送请求 HttpResponse httpResponse = httpClient.execute(httpGet); // 判断返回状态,并接收图片 if (httpResponse.getStatusLine().getStatusCode() == 200) { HttpEntity httpEntity = httpResponse.getEntity(); byte[] data = EntityUtils.toByteArray(httpEntity); bitmap = BitmapFactory .decodeByteArray(data, 0, data.length); } } catch (ClientProtocolException e) { // TODO 自动生成的 catch 块 e.printStackTrace(); } catch (IOException e) { // TODO 自动生成的 catch 块 e.printStackTrace(); } return bitmap; } // 表示任务执行之前的操作 protected void onPreExecute() { // TODO 自动生成的方法存根 super.onPreExecute(); // 下载之前显示弹出框然后下载图片,下载完会结束弹出框 progressDialog.show(); } @Override // 在这个方法里进行更新UI操作 protected void onPostExecute(Bitmap result) { // TODO 自动生成的方法存根 super.onPostExecute(result); // 给图片控件设置下载的图片 imageView.setImageBitmap(result); // 隐藏弹出框 progressDialog.dismiss(); } } }