通过HttpUrlConnection下载文件并显示进度条

时间:2023-03-09 10:01:56
通过HttpUrlConnection下载文件并显示进度条

实现效果:通过HttpUrlConnection下载文件并显示进度条

核心下载块:

int count = 0;
URL url = new URL("http://hezuo.downxunlei.com/xunlei_hezuo/thunder(127891).exe");

HttpURLConnection connection = (HttpURLConnection) url.openConnection();//建立连接
 
if (connection.getResponseCode() == HttpURLConnection.HTTP_OK) {
}else return;

totalSize = connection.getContentLength();//获取文件总大小

InputStream is = connection.getInputStream();
OutputStream os = new FileOutputStream(
Environment.getExternalStorageDirectory() + "/download.exe");
int len=0;

bar.setMax(totalSize);//设置进度条最大长度
Log.i("xiaohong", "max" + bar.getMax());

byte bs[] = new byte[1024];
while ((len = is.read(bs)) != -1) {
os.write(bs, 0, len);//写入文件
count += len;handler.sendEmptyMessage(count);

}
os.flush();
is.close();
os.close();//最后关闭输入输出流

//设置进度条及文本

final Handler handler = new Handler() {
@Override
public void handleMessage(Message msg) {
// TODO Auto-generated method stub
super.handleMessage(msg);
bar.setProgress(msg.what);
textView.setText("进度" + String.format("%.1f", msg.what * 1f / totalSize * 100) + "%");//保留一位小数点,且需注意数据在计算时应转为浮点型!
}
};