使用DownloadManager在进度条中显示下载进度

时间:2018-12-28 17:07:30

标签: android android-progressbar android-download-manager

我正在开发一个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

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 {
  ...
}