How to add button to notifications in android?

frankish picture frankish · Apr 24, 2013 · Viewed 83.7k times · Source

My app plays music and when users open notifications screen by swiping from the top of the screen ( or generally from the bottom right of the screen on tablets ), I want to present them a button to stop the currently playing music and start it again if they want.

I am not planning to put a widget on the user's home screen, but just into notifications. How can I do this?

Answer

Ruben Miquelino picture Ruben Miquelino · Mar 28, 2018

You can create an intent for the action (in this case stop playing)and that add it as an action button to your notification.

Intent snoozeIntent = new Intent(this, MyBroadcastReceiver.class);
snoozeIntent.setAction(ACTION_SNOOZE);
snoozeIntent.putExtra(EXTRA_NOTIFICATION_ID, 0);
PendingIntent snoozePendingIntent =
        PendingIntent.getBroadcast(this, 0, snoozeIntent, 0);

NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(this, CHANNEL_ID)
        .setSmallIcon(R.drawable.notification_icon)
        .setContentTitle("My notification")
        .setContentText("Hello World!")
        .setPriority(NotificationCompat.PRIORITY_DEFAULT)
        .setContentIntent(pendingIntent)
        .addAction(R.drawable.ic_snooze, getString(R.string.snooze),
                snoozePendingIntent);

Please refer to the Android documentation.