Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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);
like image 829
casolorz Avatar asked Jan 08 '19 22:01

casolorz


1 Answers

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.

like image 179
b0b Avatar answered Nov 07 '22 21:11

b0b