activity_main
<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" >
<Button
android:id="@+id/button1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_centerHorizontal="true"
android:text="下载网络图片" />
<ImageView
android:id="@+id/imageView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:layout_centerVertical="true"
android:src="@drawable/ic_launcher" />
</RelativeLayout>
MainActivity
package com.example.android_asytask_download;
import java.io.ByteArrayOutputStream;
import java.io.InputStream;
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.os.AsyncTask;
import android.os.Bundle;
import android.R.integer;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Entity;
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 {
private Button button;
private ImageView imageView;
private ProgressDialog progressDialog;
private String image_path = "http://a.hiphotos.baidu.com/image/w%3D2048/sign=7610c70c5143fbf2c52ca1238446cb80/d4628535e5dde71120a3a1f2a5efce1b9d166145.jpg";
@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(this);
progressDialog.setTitle("提示");
progressDialog.setMessage("正在下载,请稍后...");
progressDialog.setProgressStyle(progressDialog.STYLE_HORIZONTAL);// 设置进度条样式
progressDialog.setCancelable(false);// 点击不会失去焦点,直到下载结束
button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
new myTask().execute(image_path);// 执行异步任务操作
}
});
}
/**
* 使用异步任务规则 1.声明一个类继承AsyncTask类
* 2.第一个参数表示要执行的任务通常是网络的路径,第二参数表示刻度,第三个参数表示执行返回的结果
* */
public class myTask extends AsyncTask<String, Integer, Bitmap> {
// 表示任务之前操作
@Override
protected void onPreExecute() {
// TODO Auto-generated method stub
progressDialog.show();
super.onPreExecute();
}
// 表示耗时操作
@Override
protected Bitmap doInBackground(String... params) {
// TODO Auto-generated method stub
Bitmap bitmap = null;
ByteArrayOutputStream outputStream = new ByteArrayOutputStream();// 图片读取放到内存缓冲区中
InputStream inputStream = null;
HttpClient httpClient = new DefaultHttpClient();
HttpGet httpGet = new HttpGet(params[0]);
try {
HttpResponse httpResponse = httpClient.execute(httpGet);
if (httpResponse.getStatusLine().getStatusCode() == 200) {
inputStream = httpResponse.getEntity().getContent();
// 获取文件长度
long file_leagth = httpResponse.getEntity()
.getContentLength();
int len = 0;
byte[] date = new byte[1024];// 每次读取长度
int total_leagth = 0;// 已经下载的总长度
while ((len = inputStream.read(date)) != -1) {
total_leagth += len;
int value = (int) ((total_leagth / (float) file_leagth) * 100);
publishProgress(value);
outputStream.write(date, 0, len);
}
byte[]temp=outputStream.toByteArray();
bitmap=BitmapFactory.decodeByteArray(temp, 0, temp.length);
}
} catch (Exception e) {
// TODO: handle exception
} finally {
if (inputStream != null) {
try {
inputStream.close();
} catch (Exception e2) {
// TODO: handle exception
}
}
}
return bitmap;
}
@Override
protected void onProgressUpdate(Integer... values) {
// TODO Auto-generated method stub
super.onProgressUpdate(values);
progressDialog.setProgress(values[0]);//进度更新
};
// 表示更新ui操作
@Override
protected void onPostExecute(Bitmap result) {
// TODO Auto-generated method stub
imageView.setImageBitmap(result);
progressDialog.dismiss();
super.onPostExecute(result);
}
}
@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;
}
}