如何在Android下载DownloadManager下载Muliple文件(图像/视频网址)

时间:2017-04-15 15:23:15

标签: android android-download-manager

下载管理器是在android中下载单个文件的最佳方式,它还维护通知栏。但是如何通过它下载多个文件并通过进度条在通知中显示整个下载状态。

请为其推荐任何库或任何代码段。

1 个答案:

答案 0 :(得分:0)

你可以隐藏DownloadManager的通知并展示你自己的通知,这应该做你想做的事。

禁用setNotificationVisibility(DownloadManger.VISIBILITY_HIDDEN);隐藏通知。

要显示下载进度,您可以在ContentObserver数据库中注册DownloadManager以获取定期更新并使用它更新您自己的通知。

Cursor mDownloadManagerCursor = mDownloadManager.query(new DownloadManager.Query());
if (mDownloadManagerCursor != null) {
    mDownloadManagerCursor.registerContentObserver(mDownloadFileObserver);
}

ContentObserver看起来像是:

private ContentObserver mDownloadFileObserver = new ContentObserver(new Handler(Looper.getMainLooper())) {
    @Override
    public void onChange(boolean selfChange) {
        Cursor cursor = mDownloadManager.query(new DownloadManager.Query());

        if (cursor != null) {
            long bytesDownloaded = 0;
            long totalBytes = 0;

            while (cursor.moveToNext()) {
                bytesDownloaded += cursor.getLong(cursor.getColumnIndex(DownloadManager.COLUMN_BYTES_DOWNLOADED_SO_FAR));
                totalBytes += cursor.getLong(cursor.getColumnIndex(DownloadManager.COLUMN_TOTAL_SIZE_BYTES));
            }

            float progress = (float) (bytesDownloaded * 1.0 / totalBytes);
            showNotificationWithProgress(progress);

            cursor.close();
        }
    }
};

有进展的通知可以显示:

public void showNotificationWithProgress(Context context, int progress) {
    NotificationManagerCompat.from(context).notify(0,
            new NotificationCompat.Builder(context)
                    .setSmallIcon(R.mipmap.ic_launcher)
                    .setContentTitle("Downloading...")
                    .setContentText("Progress")
                    .setProgress(100, progress * 100, false)
                    .setOnGoing(true)
                    .build());
}