Search code examples
javaandroidandroid-download-manager

Check if downloads are active


So I'm using Download Manager to download multiple files in my app. I need these files to finish downloading before starting a certain activity. How can I check if there are active downloads, so I can tell the user to wait until the downloads are finished. And then, when they are finished, I need to make a button visible. I've googled this, even tried some code myself(blindly) and nothing works. If somebody can nudge me in the right direction I'd be grateful.


Solution

  • Use query() to inquire about downloads. When you call enqueue(), the return value is an ID for the download. You can query by status as well:

    Cursor c = downloadManager.query(new DownloadManager.Query()
            .setFilterByStatus(DownloadManager.STATUS_PAUSED
                    | DownloadManager.STATUS_PENDING
                    | DownloadManager.STATUS_RUNNING));
    

    To be notified when a download is finished, register a BroadcastReceiver for ACTION_DOWNLOAD_COMPLETE:

    BroadcastReceiver onComplete = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            // do something
        }
    };
    
    registerReceiver(onComplete, new IntentFilter(
            DownloadManager.ACTION_DOWNLOAD_COMPLETE));
    

    Note that you should also listen for the ACTION_NOTIFICATION_CLICKED broadcast to know when a user has clicked the notification for a running download.