javaandroidbroadcastreceiverandroid-download-managerreceiver

Android DownloadManager get filename


In my app you can download some files. I used the Android DownloadManager class for downloading. After the download is completed, it should show me a message that the file was downloaded. The problem is, there could be 2,3 or 4 downloads at the same time. My BroadcastReceiver code looks like this:

receiver_complete = new BroadcastReceiver(){
         @Override
          public void onReceive(Context context, Intent intent) {
             String action = intent.getAction();
                if (action.equals(DownloadManager.ACTION_DOWNLOAD_COMPLETE) ){
                    Toast.makeText(MainActivity.this, MainActivity.this.getString(R.string.download_finished, "Here should be the name", Toast.LENGTH_SHORT).show();
                }
         }
     };

How can I get the current filename of the finished download?

Thank you very much.


Solution

  • I think you want to put something like this inside your if block. Replace YOUR_DM with your DownloadManager instance.

    Bundle extras = intent.getExtras();
    DownloadManager.Query q = new DownloadManager.Query();
    q.setFilterById(extras.getLong(DownloadManager.EXTRA_DOWNLOAD_ID));
    Cursor c = YOUR_DM.query(q);
    
    if (c.moveToFirst()) {
        int status = c.getInt(c.getColumnIndex(DownloadManager.COLUMN_STATUS));
        if (status == DownloadManager.STATUS_SUCCESSFUL) {
            // process download
            title = c.getString(c.getColumnIndex(DownloadManager.COLUMN_TITLE));
            // get other required data by changing the constant passed to getColumnIndex
        }
    }