使用DownloadManager显示活动中的下载进度


89

我正在尝试重现DownloadManager在我的应用程序内的通知栏中显示的相同进度,但是我的进度从未发布。我正在尝试使用runOnUiThread()更新它,但是由于某种原因,它尚未更新。

我的下载:

String urlDownload = "https://dl.dropbox.com/s/ex4clsfmiu142dy/test.zip?token_hash=AAGD-XcBL8C3flflkmxjbzdr7_2W_i6CZ_3rM5zQpUCYaw&dl=1";
DownloadManager.Request request = new DownloadManager.Request(Uri.parse(urlDownload));

request.setDescription("Testando");
request.setTitle("Download");
request.allowScanningByMediaScanner();
request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
request.setDestinationInExternalPublicDir(Environment.DIRECTORY_DOWNLOADS, "teste.zip");

final DownloadManager manager = (DownloadManager) getSystemService(Context.DOWNLOAD_SERVICE);

final long downloadId = manager.enqueue(request);

final ProgressBar mProgressBar = (ProgressBar) findViewById(R.id.progressBar1);

new Thread(new Runnable() {

    @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;
            }

            final double dl_progress = (bytes_downloaded / bytes_total) * 100;

            runOnUiThread(new Runnable() {

                @Override
                public void run() {

                    mProgressBar.setProgress((int) dl_progress);

                }
            });

            Log.d(Constants.MAIN_VIEW_ACTIVITY, statusMessage(cursor));
            cursor.close();
        }

    }
}).start();

我的statusMessage方法:

private String statusMessage(Cursor c) {
    String msg = "???";

    switch (c.getInt(c.getColumnIndex(DownloadManager.COLUMN_STATUS))) {
    case DownloadManager.STATUS_FAILED:
        msg = "Download failed!";
        break;

    case DownloadManager.STATUS_PAUSED:
        msg = "Download paused!";
        break;

    case DownloadManager.STATUS_PENDING:
        msg = "Download pending!";
        break;

    case DownloadManager.STATUS_RUNNING:
        msg = "Download in progress!";
        break;

    case DownloadManager.STATUS_SUCCESSFUL:
        msg = "Download complete!";
        break;

    default:
        msg = "Download is nowhere in sight";
        break;
    }

    return (msg);
}

我的日志运行正常,而我的下载正在运行时显示“正在进行下载!” 并完成“下载完成!”,但是进度没有相同,为什么?我真的需要一些帮助,真的很感谢其他逻辑


可能是您的文件太小了,并且在进度发布之前下载完成了吗?下载查询在您的任务中返回什么?如果仅在一段时间后才执行任务,则可能在主线程上有一些其他长时间运行的操作。
Paul Lammertsma

我更新了代码,现在可以看看吗?关于文件长度不是太小,我可以在通知栏上看到下载进度
Victor Laerte 2013年

Answers:


62

您将两个整数相除:

final double dl_progress = (bytes_downloaded / bytes_total) * 100;

由于bytes_downloaded小于bytes_total(bytes_downloaded / bytes_total)将为0,因此您的进度将始终为0。

将计算更改为

final int dl_progress = (int) ((bytes_downloaded * 100l) / bytes_total);

获得整个(尽管有底限)百分位数的进度。


@AZ_感谢您的贡献。我建议您使用更详尽的解决方案添加自己的答案。
Paul Lammertsma 2014年

可以,我不想再输入一个已经被接受的答案,因为这对用户来说很困难。您可以选择不接受我的编辑:)
2014年

1
如果您的活动结束并且想要取消下载,则会收到division by zero致命错误。这就是为什么我这样做 final int dl_progress = ( bytes_total > 0 ? (int) ((bytes_downloaded * 100L) / bytes_total) : 0 );
KaHa6uc

17

Paul的回答是正确的,但下载量较大时,您将很快达到max int并开始获得负面进展。我用它来解决这个问题:

final int dl_progress = (int) ((bytes_downloaded * 100l) / bytes_total);

你是对的; 我已经修改了答案,以确保其他人不会犯同样的错误。
Paul Lammertsma,2014年

4

正如保罗所说,您将两个整数相除,结果始终小于1。

始终除法之前强制转换您的数字除法运算并返回浮点数。

不要忘记处理DivByZero。

final int dl_progress = (int) ((double)bytes_downloaded / (double)bytes_total * 100f);

4

如果有人需要使用RxJava在Kotlin中使用@Victor Laerte的问题来实现下载进度检索器,请执行以下操作:

DownloadStateRetriever.kt

class DownloadStateRetriever(private val downloadManager: DownloadManager) {

    fun retrieve(id: Long) {
        var downloading = AtomicBoolean(true)

        val disposable = Observable.fromCallable {
            val query = DownloadManager.Query().setFilterById(id)
            val cursor = downloadManager.query(query)

            cursor.moveToFirst()

            val bytesDownloaded = cursor.intValue(DownloadManager.COLUMN_BYTES_DOWNLOADED_SO_FAR)
            val bytesTotal = cursor.intValue(DownloadManager.COLUMN_TOTAL_SIZE_BYTES)

            if (isSuccessful(cursor)) downloading.set(false)
            cursor.close()

            if (bytesTotal == 0) 0.toInt() else ((bytesDownloaded * 100F) / bytesTotal).toInt()
        }
                .subscribeOn(Schedulers.newThread())
                .delay(1, TimeUnit.SECONDS)
                .repeatUntil { !downloading.get() }
                .subscribe {
                    Timber.i("Subscribed to $id. progress: $it")
                }
    }

    private fun isSuccessful(cursor: Cursor) = status(cursor) == DownloadManager.STATUS_SUCCESSFUL

    private fun status(cursor: Cursor) = cursor.intValue(DownloadManager.COLUMN_STATUS)
}

我为光标添加了扩展名,以使代码更清晰:

CursorExtensions.kt

import android.database.Cursor

fun Cursor.column(which: String) = this.getColumnIndex(which)
fun Cursor.intValue(which: String): Int = this.getInt(column(which))
fun Cursor.floatValue(which: String): Float = this.getFloat(column(which))
fun Cursor.stringValue(which: String): String = this.getString(column(which))
fun Cursor.doubleValue(which: String): Double = this.getDouble(column(which))

By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.