android AsyncTask异步下载并更新进度条

时间:2021-08-16 08:36:21
AsyncTask异步下载并更新进度条
 
 //如果不是很明白请看上篇文章的异步下载
AsyncTask<String, Integer, String>  

第一个参数:String 传入的是需要下载的地址

第二个参数:Integer 是进度条的进度 

第三个参数:String 下载后的结果,如果您下载的是一张图片,可以将它改成BitMap

示例代码如下:

package com.example.testcctv;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL; import org.apache.http.HttpStatus; import android.os.AsyncTask;
import android.util.Log;
import android.widget.ProgressBar; /*****************************************************************************************************************************************
* 异步线程下载类 参数说明: 第一个参数:String 传入的是需要下载的地址 第二个参数:Integer 是进度条的进度 第三个参数:String
* 下载后的结果,如果您下载的是一张图片,可以将它改成BitMap
*****************************************************************************************************************************************/
public class DownloadAsyncTask extends AsyncTask<String, Integer, String> { private final ProgressBar bar;
private int count = 0; public DownloadAsyncTask(ProgressBar bar) {
super();
this.bar = bar;
} @Override
protected String doInBackground(String... params) {
try {
URL url = new URL(params[0]);
HttpURLConnection connection = (HttpURLConnection) url
.openConnection();
connection.setConnectTimeout(10 * 1000);
connection.connect();
if (connection.getResponseCode() == HttpStatus.SC_OK) {
bar.setMax(connection.getContentLength());
File file = new File(params[1]);
file.createNewFile();
InputStream inputStream = connection.getInputStream();
ByteArrayOutputStream arrayOutputStream = new ByteArrayOutputStream();
byte[] buffer = new byte[10 * 1024];
while (true) {
int len = inputStream.read(buffer);
publishProgress(len);
if (len == -1) {
break;
}
arrayOutputStream.write(buffer, 0, len);
}
arrayOutputStream.close();
inputStream.close(); byte[] data = arrayOutputStream.toByteArray();
FileOutputStream fileOutputStream = new FileOutputStream(file);
fileOutputStream.write(data);
fileOutputStream.close();
} } catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return "下载完成";
} @Override
protected void onCancelled() {
// TODO Auto-generated method stub
super.onCancelled();
} @Override
protected void onPostExecute(String result) {
Log.v("Fover", result);
super.onPostExecute(result);
} @Override
protected void onPreExecute() {
// TODO Auto-generated method stub
super.onPreExecute();
} @Override
protected void onProgressUpdate(Integer... values) {
count += values[0];
bar.setProgress(count);
super.onProgressUpdate(values);
} } 使用方法: //第一个值是下载地址,第二个值是保存地址
String[] downLoadPath = {
HTTPURL,
Environment.getExternalStorageDirectory()
+ "/dujinyang/dudu.apk" };
DownloadAsyncTask asynTask = new DownloadAsyncTask(progressBar);
asynTask.execute(downLoadPath);