Search code examples
androidnotifications

How to add pause and cancel button to custom download notification android


I have created a custom notification for Downloading an mp3 file from a given URL. Now I need to know how to add pause and cancel buttons to the custom notification I have created.

Here is the partial code for custom Notification:

if (!downloadUrl.toString().isEmpty()) {
    DownloadManager.Request request = new DownloadManager.Request(Uri.parse(downloadUrl));
    request.setMimeType("audio/MP3");
    request.setTitle(vMeta.getTitle());
    request.allowScanningByMediaScanner();
    request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_HIDDEN);
    request.setDestinationInExternalPublicDir(storage, vMeta.getTitle() + extension);
    final DownloadManager manager = (DownloadManager) getSystemService(Context.DOWNLOAD_SERVICE);

    final long id = manager.enqueue(request);

    registerReceiver(new DownloadReceiver(id, storage, vMeta.getTitle() + extension),
        new IntentFilter(DownloadManager.ACTION_DOWNLOAD_COMPLETE));
    mBuilder = new NotificationCompat.Builder(getApplicationContext());
    Intent intent = new Intent();
    PendingIntent pendingIntent = PendingIntent.getActivity(getApplicationContext(), 0, intent, 0);
    mBuilder.setContentIntent(pendingIntent);
    mBuilder.setSmallIcon(R.drawable.ic_music_video_white_24dp);
    mBuilder.setContentTitle("Downloading");
    mBuilder.setContentText(vMeta.getTitle());
    mBuilder.setOngoing(false);
    //mBuilder.addAction();
    mNotificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);

    new Thread(new Runnable() {
        @Override
        public void run() {

            boolean downloading = true;

            while (downloading) {
                DownloadManager.Query q = new DownloadManager.Query();
                q.setFilterById(id);
                Cursor cursor = manager.query(q);
                cursor.moveToFirst();
                if (cursor != null && cursor.moveToFirst()) {
                    bytes_downloaded = cursor.getInt(cursor
                        .getColumnIndex(DownloadManager.COLUMN_BYTES_DOWNLOADED_SO_FAR));
                    bytes_total = cursor.getInt(cursor.getColumnIndex(DownloadManager.COLUMN_TOTAL_SIZE_BYTES));
                    dl_progress = (int)((bytes_downloaded * 100l) / bytes_total);
                }
                mNotificationManager.notify(001, mBuilder.build());
                if (cursor.getInt(cursor.getColumnIndex(DownloadManager.COLUMN_STATUS)) == DownloadManager.STATUS_SUCCESSFUL) {
                    downloading = false;
                    mBuilder.setContentTitle("Download complete")
                        .setOngoing(false)
                        .setAutoCancel(true)
                        .setProgress(100, 100, false);
                    mNotificationManager.notify(001, mBuilder.build());
                }

                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        mBuilder.setContentTitle("Downloading: " + dl_progress + "%");
                        mBuilder.setProgress(100, dl_progress, false);
                        mNotificationManager.notify(001, mBuilder.build());

                    }
                });

                cursor.close();
            }

        }
    }).start();
}

And this the code for my Downloader class:

public class DownloadReceiver extends BroadcastReceiver {
    private long id;
    private String dirType;
    private String subPath;

    public DownloadReceiver(long id, String dirType, String subPath) {
        this.id = id;
        this.dirType = dirType;
        this.subPath = subPath;
    }

    @Override
    public void onReceive(Context context, Intent intent) {
        if (intent.getLongExtra(DownloadManager.EXTRA_DOWNLOAD_ID, -1) == id) {
            MainActivity.this.unregisterReceiver(this);
            File oldFile = new File(Environment.getExternalStoragePublicDirectory(dirType), subPath);
            String newSubPath = subPath.substring(0, subPath.lastIndexOf('.')) + "|MEGA" + ".mp3";
            File newFile = new File(Environment.getExternalStoragePublicDirectory(dirType), newSubPath);
            Boolean result = oldFile.renameTo(newFile);
            Toast.makeText(context, "Download " + (result ? "succeeded" : "failed"), Toast.LENGTH_SHORT).show();
        }
    }
}

Solution

  • You need to set particular action to notification with media control you can add particular action with relative pending intent

    .addAction(R.drawable.ic_prev, "Previous", prevPendingIntent) 
    .addAction(R.drawable.ic_pause, "Pause", pausePendingIntent) 
    .addAction(R.drawable.ic_next, "Next", nextPendingIntent) 
    

    You also need to set media style using below code

     .setStyle(MediaNotificationCompat.MediaStyle()
     .setShowActionsInCompactView(1 /* #1: pause button \*/)
     .setMediaSession(mMediaSession.getSessionToken()))
    

    You can also check this link for more instructions.