How can I get the X button for stopping on the media style notification on Android P? Code Answer

Hello Developer, Hope you guys are doing great. Today at Tutorial Guruji Official website, we are sharing the answer of How can I get the X button for stopping on the media style notification on Android P? without wasting too much if your time.

The question is published on by Tutorial Guruji team.

I’m trying to show the X on the MediaStyle Notification Android P. I see a lot of posts basically saying this won’t work on API 21 and higher I think but here is screenshot of an app showing it:

enter image description here

I’ve tried this code below but it doesn’t show it:

    Notification notification = new NotificationCompat.Builder(getApplicationContext(), TESTID)
            .setSmallIcon(R.drawable.ic_launcher_background)
            .setContentTitle("Track title")
            .setContentText("Artist - Album")
            .addAction(R.drawable.ic_fast_forward_black_24dp, "fwd", pi)
            .addAction(R.drawable.ic_fast_forward_black_24dp, "fwd", pi)
            .addAction(R.drawable.ic_fast_forward_black_24dp, "fwd", pi)
            .setLargeIcon(BitmapFactory.decodeResource(getResources(), R.drawable.vectors_525058875))
            .setAutoCancel(false)
            .setStyle(new MediaStyle()
                    .setMediaSession(mediaSessionCompat.getSessionToken()).setShowCancelButton(true).setCancelButtonIntent(pi))
            .build();
    notificationManager.notify(300, notification);

Answer

You must use very little known class DecoratedMediaCustomViewStyle that is similar to MediaStyle except that it let you customize what you display into the content area using a RemoteViews. The trick is to replicate the MediaStyle layout (you can copy it from the support lib) and customize it, adding an X button for example.

However, there are 2 caveats:

  • DecoratedMediaCustomViewStyle does not render properly on Xiaomi devices (it looks all white). So you must have a fallback to MediaStyle on these devices
  • setting color for TextView in the custom RemoteViews of DecoratedMediaCustomViewStyle does not work, either set in XML or by code. So you are stuck with default text color (black).

Update 2020: DecoratedMediaCustomViewStyle makes MIUI 12 Crash in SystemUI. MIUI is mostly found on Xiaomi/Redmi devices.

We are here to answer your question about How can I get the X button for stopping on the media style notification on Android P? - If you find the proper solution, please don't forgot to share this with your team members.

Related Posts

Tutorial Guruji