Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can Android show action icons in collapsed notifications?

Tags:

The default behavior to see actions in notifications is by expanding a notification. Can I show them without the need to expand them?

like image 543
qbait Avatar asked Jul 05 '18 11:07

qbait


People also ask

Can Android change notification icons?

1 Tap Notification Settings on the notification panel or tap the Settings app. 2 Tap Notifications. 3 Tap App icon badges.

How do I collapse notifications on Android?

If you tap a notification, the app that sent it will open. To dismiss a notification, touch it and swipe left or right. Tap the dismiss icon to dismiss all notifications. On newer versions of Android, you can manage some notifications from the lock screen.

Does Android have banner notifications?

Tap a type of notification. Choose your options: Choose Alerting or Silent. To see a banner for alerting notifications when your phone is unlocked, turn on Pop on screen.


1 Answers

Yes! :) You can, on Android 5.0+ (since API level 21).

Here is a working example:

 if (Build.VERSION.SDK_INT >= 26)    // Android 8 or later?
 {
     builder = new Notification.Builder (this, Const.NOTIF_CHANNEL_ID);
 }
 else
 {
     builder = new Notification.Builder (this);
 }

 builder.setSmallIcon (R.drawable.ic_notif_icon, 0)
     .setVisibility (Notification.VISIBILITY_PUBLIC)
     .setCategory (Notification.CATEGORY_ALARM)
     .setContentIntent (pendingMainActionIntent)
     .setOngoing (true)
     .addAction (R.drawable.ic_button1, "BUTTON 1", pButton1Intent)
     .addAction (R.drawable.ic_button2, "BUTTON 2", pButton2Intent)
     .addAction (R.drawable.ic_button3, "BUTTON 3", pButton3Intent)
     // Apply the media style template so that we get buttons on the notification widget even when it's in the collapsed mode
     .setStyle (new Notification.MediaStyle ().setShowActionsInCompactView (0, 1, 2));

Note mainly the last line, which ensures what you want:

.setStyle (new Notification.MediaStyle ().setShowActionsInCompactView (0, 1, 2))

Also note the parameters passed to setShowActionsInCompactView. If you, for example, only wanted BUTTON 2 and BUTTON 3 to be shown (not BUTTON 1), you would do it like this:

.setShowActionsInCompactView (1, 2) 

Tested on Android 8.1, Google Pixel 2, and Samsung S9, but code should work on Android 5-7 and other phones too. Enjoy.

UPDATE: The previous code worked on Android 8 only. Made it support earlier versions too. Also on Android 8, you should not forget to call builder.setChannelId (Const.NOTIF_CHANNEL_ID) right below the code I posted.

UPDATE 2: Added a missing bracket after setShowActionsInCompactView and improved indentation.

like image 114
deLock Avatar answered Oct 11 '22 16:10

deLock