我希望这将是我错过的一件愚蠢的事情,但我一直在用头撞键盘,试图找出我哪里出错了。
我正在尝试从新线程中的 DownloadManager 更新 ProgressBar。这一直正常工作,直到大约一半,ProgressBar 重置回开始。通过放入一些调试代码,我将问题隔离到这一行:
final int dl_progress = (bytes_downloaded*100)/bytes_total;
dl_progress
文件下载中途变成负数!相关代码块和日志输出如下:
@Override
public void run() {
boolean downloading = true;
while (downloading) {
DownloadManager.Query q = new DownloadManager.Query();
q.setFilterById(downloadId);
Cursor cursor = manager.query(q);
cursor.moveToFirst();
int bytes_downloaded = cursor.getInt(cursor
.getColumnIndex(DownloadManager.COLUMN_BYTES_DOWNLOADED_SO_FAR));
int bytes_total = cursor.getInt(cursor
.getColumnIndex(DownloadManager.COLUMN_TOTAL_SIZE_BYTES));
if (cursor.getInt(cursor.getColumnIndex(DownloadManager.COLUMN_STATUS)) == DownloadManager.STATUS_SUCCESSFUL) {
downloading = false;
getActivity().runOnUiThread(new Runnable() {
public void run() {
mProgressBar.setVisibility(View.INVISIBLE);
}
});
}
final int dl_progress = (bytes_downloaded*100)/bytes_total;
Log.d("Download", bytes_downloaded + " of " + bytes_total + " (" + dl_progress + "%)");
getActivity().runOnUiThread(new Runnable() {
@Override
public void run() {
mProgressBar.setProgress((int) dl_progress);
}
});
cursor.close();
}
}
这是调试:
D/Download(18228): 7614 of 38577287 (0%)
D/Download(18228): 4226950 of 38577287 (10%)
D/Download(18228): 8578734 of 38577287 (22%)
D/Download(18228): 13207130 of 38577287 (34%)
D/Download(18228): 16539590 of 38577287 (42%)
D/Download(18228): 22287422 of 38577287 (-53%)
D/Download(18228): 28363958 of 38577287 (-37%)
D/Download(18228): 32550806 of 38577287 (-26%)
D/Download(18228): 38577287 of 38577287 (-11%)
我确定是我在做一些愚蠢的事情,但是在这种情况下我看不到树木的树木,有人能解释一下吗?
非常感谢你。