将上一个项目中的进度条改为能显示进度的进度条。
MainActivity.java:
package net.csdn.leigo.asynctask;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
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 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.View;
import android.widget.ImageView;
public class MainActivity extends Activity {
private ProgressDialog progressDialog;
private ImageView mDownloadImg;
private static final String IMG_URL = "http://p1.qhimg.com/d/_onebox/search.png";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mDownloadImg = (ImageView) findViewById(R.id.iv_download);
progressDialog = new ProgressDialog(this);
progressDialog.setTitle("提示信息");
progressDialog.setMessage("正在下载中,请稍侯...");
progressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
}
public void downloadImg(View v) {
new MyAsyncTask().execute(IMG_URL);
}
class MyAsyncTask extends AsyncTask<String, Integer, Bitmap> {
// 任务执行之前的操作
@Override
protected void onPreExecute() {
super.onPreExecute();
progressDialog.show();
}
@Override
protected void onProgressUpdate(Integer... values) {
super.onProgressUpdate(values);
progressDialog.setProgress(values[0]);
}
// 主要完成耗时操作
@Override
protected Bitmap doInBackground(String... params) {
Bitmap bitmap = null;
InputStream inputStream = null;
ByteArrayOutputStream baos = new ByteArrayOutputStream();
try {
// 使用网络链接类HttpClient类完成对网络数据的读取
HttpClient httpClient = new DefaultHttpClient();
// params[0] 代表连接的url
HttpGet httpGet = new HttpGet(params[0]);
HttpResponse httpResponse = httpClient.execute(httpGet);
if (httpResponse.getStatusLine().getStatusCode() == 200) {
HttpEntity httpEntity = httpResponse.getEntity();
inputStream = httpEntity.getContent();
// 获得文件总长度
long totalSize = httpEntity.getContentLength();
int len = 0;
int count = 0;
byte[] buffer = new byte[1024];
while ((len = inputStream.read(buffer)) != -1) {
baos.write(buffer, 0, len);
count += len;
// 调用publishProgress公布进度,最后onProgressUpdate方法将被执行
publishProgress((int) ((count / (float) totalSize) * 100));
// 为了演示进度,休眠100毫秒
Thread.sleep(100);
}
byte[] data = baos.toByteArray();
bitmap = BitmapFactory.decodeByteArray(data, 0, data.length);
}
} catch (Exception e) {
e.printStackTrace();
} finally {
if (inputStream != null) {
try {
baos.close();
inputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
return bitmap;
}
// 主要是更新UI操作
@Override
protected void onPostExecute(Bitmap result) {
super.onPostExecute(result);
progressDialog.dismiss();
mDownloadImg.setImageBitmap(result);
}
}
}