我正在开发一个Android应用,其中我正在使用DownloadManager
从服务器下载文件。
问题
文件下载正在进行中,我想通过progress bar
显示下载进度。文件下载成功,但无法显示下载进度。
我用来显示进度的代码
private void startAppDownload() {
...
// code to show download progress
new Thread(new Runnable() {
@Override
public void run() {
boolean isDownloading = true;
int downloadStatus, totalBytesDownloaded, totalBytes;
DownloadManager.Query downloadQuery = new DownloadManager.Query();
downloadQuery.setFilterById(downloadID);
Cursor cursor = downloadManager.query(downloadQuery);
cursor.moveToFirst();
while (isDownloading) {
totalBytesDownloaded = cursor.getInt(
cursor.getColumnIndex(DownloadManager.COLUMN_BYTES_DOWNLOADED_SO_FAR)
);
totalBytes = cursor.getInt(
cursor.getColumnIndex(DownloadManager.COLUMN_TOTAL_SIZE_BYTES)
);
downloadStatus = cursor.getInt(cursor.getColumnIndex(DownloadManager.COLUMN_STATUS));
if(downloadStatus == DownloadManager.STATUS_SUCCESSFUL) {
isDownloading = false;
}
final int downloadProgress = (int) ((double)totalBytesDownloaded / (double)totalBytes * 100f);
runOnUiThread(new Runnable() {
@Override
public void run() {
downloadProgressBar.setProgress(downloadProgress);
}
});
}
cursor.close();
}
}).start();
}
我记录了totalBytesDownloaded
变量,但它始终为zero
,而totalBytes
变量始终为-1
。
这会导致downloadProgress
变量始终为zero
,因此progress bar
显示没有进度。
问题
我在这里做错了什么?为什么totalBytesDownloaded
变量总是等于zero
,而totalBytes
变量总是等于-1
?
答案 0 :(得分:1)
您遇到逻辑错误,查询不在更新用户界面的while循环中
abstract class AbstractObject {
...
public static counter = ?
}
class Object1 extends AbstractObject {
...
}
class Object2 extends AbstractObject {
...
}
class Object3 extends Object1 {
...
}
class Object4 extends Object1 {
...
}
class Object7 extends Object2 {
...
}