18

I have a notification that I'm trying to update by reusing the same Notification Builder, but there's no way to clear the buttons, you can only call addAction. Not using the same Builder results in the notification flashing, which is undesirable. Are there any solutions to this? I'm using NotificationCompat from the v4 support library.

Jess
  • 42,368
  • 6
  • 37
  • 51

3 Answers3

7
notificationBuilder.mActions.clear();

It's actually public ArrayList<Action>, so you can do whataver you want with it.

Pitel
  • 5,334
  • 7
  • 45
  • 72
  • 2
    It doesn't work for me:( I get an error: "mActions can only be accessed from within the same library group (group=com.android.support)" – user2146414 Nov 15 '19 at 13:13
2

You have two options to achieve that:

  1. Use a custom layout (just copy the design of the native notification if you want to) and then use this in a RemoteView and just make views visible or hide them. With remoteView.setViewVisibility(...) for example... Or change the text of the buttons...
  2. Use reflection to clear the builders actions. Would work like following:

    try {
        //Use reflection to remove all old actions
        Field f = mNotificationBuilder.getClass().getDeclaredField("mActions");
        f.setAccessible(true);
        f.set(mNotificationBuilder, new ArrayList<>());
    } 
    catch (NoSuchFieldException e) {} 
    catch (IllegalAccessException e) {}
    
prom85
  • 16,896
  • 17
  • 122
  • 242
0

Starting API 24 you can use method setActions() and update icon, text and pending intent.

Notification.Action.Builder builder = new Notification.Action.Builder( Icon.createWithResource( this, R.drawable.ic_pause) , getString( R.string.pause ), PendingIntent.getBroadcast( this, 1, new Intent( TIMER_PAUSE ), 0 ) );
Notification.Action action = builder.build();
...
notification_builder.setActions( action );
Notification notification = notification_builder.build();
NotificationManager nm = (NotificationManager) getSystemService( Context.NOTIFICATION_SERVICE );
nm.notify( 1, notification );
Style-7
  • 985
  • 12
  • 27