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


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


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

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

然后,修改doInBackground方法如下:

@Override
		protected 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 block
						e.printStackTrace();
					}
				}
			}
			return bitmap;
		}

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

最后在onProgressUpdate中加入:

dialog.setProgress(values[0]);

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

你可能感兴趣的:(多线程,android,AsyncTask)