limlim limlim - 1 year ago 97
Android Question

Adding a terminate playback button using Android L Notification.MediaStyle

I want to create a Media Playback notification using the new Android L MediaStyle template. Now, I succeeded doing so perfectly well for actions like previous, play, pause, next (by using

, but I couldn't find a way to add a "close" button like in the Android Notifications Documentation screenshot:

enter image description here

Is there a neat way to achieve this? I want the "close" button to terminate the currently playing playback, clear the playback notification, and be located as in the attached screenshot.

Answer Source


When using the Support Library's version of this notification style, i.e. NotificationCompat.MediaStyle, there is the setShowCancelButton() button.

This will add the close button, but only on versions prior to Lollipop, to work around a bug with notifications that cannot be made dismissable after being displayed as part of a foreground service.

In Lollipop the preferred option is to just being able to dismiss the notification (when the audio is paused) instead of having a custom button to do that.


From taking a look at the source code of Notification.MediaStyle class it would seem that there is currently no support for such a button in the MediaStyle notification style:

    private RemoteViews makeMediaBigContentView() {
        final int actionCount = Math.min(mBuilder.mActions.size(), MAX_MEDIA_BUTTONS);
        RemoteViews big = mBuilder.applyStandardTemplate(getBigLayoutResource(actionCount),
                false /* hasProgress */);

        if (actionCount > 0) {
            for (int i = 0; i < actionCount; i++) {
                final RemoteViews button = generateMediaActionButton(mBuilder.mActions.get(i));
                big.addView(, button);
        big.setViewVisibility(, View.GONE);
        return big;

This matches with the layout it inflates (notification_template_material_big_media), which contains:

  • A layout for the media image.
  • A LinearLayout for three text lines.
  • A LinearLayout where the media actions are added.
  • An ImageView to show the divider line between these two.

but nothing else.

It would appear that the close button in the documentation page is just an artist's rendition (Google Play Music doesn't include it, either).

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download