點擊暫停后,進度值會超過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();
}
}
}