Search code examples
androidandroid-notificationsandroid-download-managercancel-button

Android N - Download Manager Notification Cancel Button


Android N has a new Cancel Button in the Download Manager Notification.

I would like to excecute some code in my app to stop a progressbar when the user presses this button. If any, which method is called?

Please also note that the Intent filter action DownloadManager.ACTION_NOTIFICATION_CLICKED is triggered only when the user clicks on the notification itself, not when he/she clicks of the Cancel button.

 if_downloadManager = new IntentFilter();
    if_downloadManager.addAction(DownloadManager.ACTION_DOWNLOAD_COMPLETE);
    if_downloadManager.addAction(DownloadManager.ACTION_NOTIFICATION_CLICKED);

    br_downloadManager = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            String action = intent.getAction();

            if (DownloadManager.ACTION_DOWNLOAD_COMPLETE.equals(action)) {
                ....
            }

            if (DownloadManager.ACTION_NOTIFICATION_CLICKED.equals(action)) {
                // This code is not executed when the user presses the Cancel Button in the Download Manager Notification
            }       
        }
    };

Thanks in advance.


Solution

  • I had the same problem in my app where I had to handle the Cancel button on the downloads notification and downloads deletion from the native Downloads app.

    Turns out that if you register a receiver with the intent filter: DownloadManager.ACTION_DOWNLOAD_COMPLETE, it's always called when the cancel or downloads deletion is initiated.

    So, How to differentiate between Download Complete and Download Deletion?

    Well, it's quite simple:

    1. Get the Download Manager ID (dmid) of the canceled download from the Intent data that is passed as an argument to the handleReceive function of your BroadcastReceiver.
    2. Using that dmid query the DownloadManager for its status.
    3. The DownloadManager would either return null for that dmidor the value for DownloadManager.STATUS_SUCCESSFUL column would be false for the said download.
    4. Once you know this, you can do whatever you want!

    For reference you can see how I did it here:

    1. My Receiver's declaration in AndroidManifest.xml: https://github.com/edx/edx-app-android/blob/8a75d0dba6b8570956eac5c21c99ecd5020c81ae/OpenEdXMobile/AndroidManifest.xml#L265-L271
    2. My Reciever's actual code that handles this case: https://github.com/edx/edx-app-android/blob/d986a9ab64e7a0f999024035ec6fcbdb3428f613/OpenEdXMobile/src/main/java/org/edx/mobile/module/download/DownloadCompleteReceiver.java#L50-L62