下載進(jìn)度值會(huì)超過100%
如果一次性下載完apk文件,則進(jìn)度值正常
如果中間有過暫停,則下載進(jìn)度值會(huì)超過100%,但是文件下載下來是正常的,懷疑是暫停保存各個(gè)線程已完成進(jìn)度的時(shí)候有問題。
哪位仁兄能看出問題所在:
@Override
public void run() {
// 設(shè)置線程下載位置
try {
URL url = new URL(threadInfo.getUrl());
con = (HttpURLConnection) url.openConnection();
con.setReadTimeout(5000);
con.setRequestMethod("GET");
// 設(shè)置下載位置
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");
// 在讀寫的時(shí)候跳過設(shè)置好的字節(jié)數(shù),從下一個(gè)字節(jié)數(shù)開始讀寫
raf.seek(start);
Intent intent = new Intent(DownService.ACTION_UPDATE);
progress += threadInfo.getProgress();// 線程完成進(jìn)度
// 開始下載
if (HttpStatus.SC_PARTIAL_CONTENT == con.getResponseCode()) {
// 讀取數(shù)據(jù)
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);
// 整個(gè)文件的完成進(jìn)度
progress += len;
// 當(dāng)前線程完成的進(jìn)度
threadInfo.setProgress(threadInfo.getProgress() + len);
// 每隔500毫秒發(fā)送一次廣播刷新進(jìn)度條
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());
// 發(fā)送廣播更新進(jìn)度條
context.sendBroadcast(intent);
}
// 下載暫停時(shí),保存下載進(jìn)度
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;
}
}
// 標(biāo)識(shí)當(dāng)前線程執(zhí)行完畢
isFinish = true;
// 檢查下載任務(wù)是否執(zhí)行完畢
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();
}
}
}
2016-03-17
已經(jīng)搞定了,根據(jù)教程來,發(fā)現(xiàn)多加了一次,每次暫停之后發(fā)現(xiàn)進(jìn)度值是暫停前的兩倍
2016-03-17
建議傳遞回去的不要是百分比,而是把每次獲取的length傳遞回去,holder.ProgressBar.incrementProgressBy(length);方法更新進(jìn)度條,這樣比較準(zhǔn)確。建議使用listview局部更新