上一个blog实现了图片下载功能,但没有实现进度条,这里我们加上这个功能。


首先,将三个泛型参数的第二个改为Integer,表示进度条的刻度为int

public class MyTask extends AsyncTask<String, Integer, Bitmap>

然后,修改doInBackground方法如下:

@Overrideprotected Bitmap doInBackground(String... params) {// TODO Auto-generated method stub// 完成对图片的下载Bitmap bitmap = null;ByteArrayOutputStream outputStream = new ByteArrayOutputStream();InputStream inputStream = null;try {HttpClient httpClient = new DefaultHttpClient();HttpGet httpGet = new HttpGet(params[0]);HttpResponse httpResponse = httpClient.execute(httpGet);if (httpResponse.getStatusLine().getStatusCode() == 200) {inputStream = httpResponse.getEntity().getContent();// 先获得文件的长度long file_length = httpResponse.getEntity().getContentLength();int len = 0;byte[] data = new byte[1024];int total_length = 0;while (-1 != (len = inputStream.read(data, 0, 1024))) {total_length += len;int value = (int) ((total_length / (float) file_length) * 100);//向onPrgressUpdate传递参数publishProgress(value);outputStream.write(data, 0, len);}byte[] result = outputStream.toByteArray();bitmap = BitmapFactory.decodeByteArray(result, 0, result.length);}} catch (Exception e) {// TODO: handle exception} finally {if (inputStream != null) {try {inputStream.close();} catch (IOException e) {// TODO Auto-generated catch blocke.printStackTrace();}}}return bitmap;}

主要是修改了进度条的参数

最后在onProgressUpdate中加入:

dialog.setProgress(values[0]);

这行代码主要是处理上面的函数中publishProgress穿过来的参数。

更多相关文章

  1. Retrofit2的使用
  2. http上传文件到网络核心代码
  3. 一起学android之SimpleAdapter使用(13)
  4. Android(安卓)ListView实现快速定位联系人功能【转发】
  5. Android如何通过scheme跳转界面
  6. Android学习笔记:Activity-Spinner
  7. 几个Android常见wraning警告处理方法
  8. Android(安卓)的网络编程(4)-HttpClient接口
  9. Android中比较常见的Java super关键字

随机推荐

  1. android bks证书生成方式
  2. android Fragment 懒加载布局
  3. android:app接收adb发送的命令并显示
  4. 获取手机分辨率(屏幕大小)
  5. android中模拟http协议表单上传
  6. Android调用手机系统自带录音功能实现语
  7. Toasts | Android(安卓)Developers
  8. Android(安卓)广播内部机制详解(三)
  9. Android(安卓)中使用MediaRecorder进行录
  10. Android(安卓)Bitmap用法总结