Search code examples
androidandroid-download-manager

How to download Muliple files (image/video url) by DownloadManager in Android


Download Manager is the best way to download single file in android, It maintain Notification bar also.but how i can download Multiple files by it and show the whole downloading status by progressing bar in Notification.

Please suggest any library for it or any code snippet.


Solution

  • You can probably hide the DownloadManager's notification and show your own, that should do what you want.

    To disable setNotificationVisibility(DownloadManger.VISIBILITY_HIDDEN); to hide the notification.

    To show download progress, you can register a ContentObserver on DownloadManager's database to get periodic updates and update your own notification with it.

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

    And the ContentObserver will look something like:

    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();
            }
        }
    };
    

    And the notification with progress can be shown with:

    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());
    }