【Android】Async异步任务之添加进度条

来源:互联网 发布:hadoop与python 编辑:程序博客网 时间:2024/05/16 12:10


上一个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穿过来的参数。

原创粉丝点击