【Android】Async异步任务之添加进度条
16lz
2021-01-25
上一个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穿过来的参数。
更多相关文章
- Retrofit2的使用
- http上传文件到网络核心代码
- 一起学android之SimpleAdapter使用(13)
- Android(安卓)ListView实现快速定位联系人功能【转发】
- Android如何通过scheme跳转界面
- Android学习笔记:Activity-Spinner
- 几个Android常见wraning警告处理方法
- Android(安卓)的网络编程(4)-HttpClient接口
- Android中比较常见的Java super关键字