Jess
Jess

Reputation: 42938

Changing the action buttons on a notification

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.

Upvotes: 19

Views: 4031

Answers (3)

Style-7
Style-7

Reputation: 1238

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 );

Upvotes: 0

Pitel
Pitel

Reputation: 5403

notificationBuilder.mActions.clear();

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

Upvotes: 7

prom85
prom85

Reputation: 17878

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) {}
    

Upvotes: 3

Related Questions