下载进度值会超过100%
如果一次性下载完apk文件,则进度值正常
如果中间有过暂停,则下载进度值会超过100%,但是文件下载下来是正常的,怀疑是暂停保存各个线程已完成进度的时候有问题。
哪位仁兄能看出问题所在:
@Override
public void run() {
// 设置线程下载位置
try {
URL url = new URL(threadInfo.getUrl());
con = (HttpURLConnection) url.openConnection();
con.setReadTimeout(5000);
con.setRequestMethod("GET");
// 设置下载位置
int start = threadInfo.getStart() + threadInfo.getProgress();
con.setRequestProperty("Range", "bytes=" + start + "-"
+ threadInfo.getEnd());
// 文件写入路径
String path = File.separator + Constants.FILE_DOWNLOAD
+ File.separator + fileInfo.getFileName();
File downFile = FileUtils.getAppFile(context, path);
raf = new RandomAccessFile(downFile, "rwd");
// 在读写的时候跳过设置好的字节数,从下一个字节数开始读写
raf.seek(start);
Intent intent = new Intent(DownService.ACTION_UPDATE);
progress += threadInfo.getProgress();// 线程完成进度
// 开始下载
if (HttpStatus.SC_PARTIAL_CONTENT == con.getResponseCode()) {
// 读取数据
is = con.getInputStream();
byte[] buffer = new byte[1024 * 4];
int len = -1;
long time = System.currentTimeMillis();
while ((len = is.read(buffer)) != -1) {
// 写入文件
raf.write(buffer, 0, len);
// 整个文件的完成进度
progress += len;
// 当前线程完成的进度
threadInfo.setProgress(threadInfo.getProgress() + len);
// 每隔500毫秒发送一次广播刷新进度条
if (System.currentTimeMillis() - time > 1000) {
time = System.currentTimeMillis();
int percent = (int) (progress * 100 / fileInfo
.getLength());
String str = fileInfo.getFileName() + " ";
str += threadInfo.getThreadId();
str += " progress:" + progress;
str += " tp:" + threadInfo.getProgress();
str += " 差:" + (fileInfo.getLength() - progress);
str += " percent:" + percent;
LogUtils.i(str);
intent.putExtra(PROGRESS, percent);
intent.putExtra(FILE_ID, fileInfo.getId());
// 发送广播更新进度条
context.sendBroadcast(intent);
}
// 下载暂停时,保存下载进度
if (isPause) {
isRuning = false;
String str = fileInfo.getFileName() + " ";
str += threadInfo.getThreadId();
str += " progress:" + progress;
str += " tp:" + threadInfo.getProgress();
str += " 差:" + (fileInfo.getLength() - progress);
str += " pause ";
LogUtils.i(str);
dao.updateThread(threadInfo);
return;
}
}
// 标识当前线程执行完毕
isFinish = true;
// 检查下载任务是否执行完毕
checkAllThreadFinished();
}
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
if (is != null) {
is.close();
}
if (raf != null) {
raf.close();
}
if (con != null) {
con.disconnect();
}
} catch (Exception e2) {
e2.printStackTrace();
}
}
}