Search code examples
androidnotificationsbroadcastreceiver

Multiple Notification with dismiss notification action button


I have an app which associates some entities with a unique ID and notifies about the entities to the user, which I'm gonna use notificationID to be the same as entity ID.

I have built a notification with a dismiss action based on the following sample solution exactly without any modification.

So far things are going well until I try to create 2 notifications with different ID using the sample. A problem arises in that the dismiss button only receives the notificationID of the first notification:

The first notification behaves normally as expected.

But the second notification's getExtra() in BroadcastReceiver takes the notificationID of the FIRST notification instead and cancelling the notification just keeps cancelling the first notification.

My create Notification function, I just call this function twice with different IDs:

void createNoti(int NOTIFICATION_ID){

    Intent buttonIntent = new Intent(context, ButtonReceiver.class);
    buttonIntent.putExtra("notificationId", NOTIFICATION_ID);

    PendingIntent btPendingIntent = PendingIntent.getActivity(getApplicationContext(), 0, buttonIntent, 0);

    NotificationCompat.Builder mb = new  NotificationCompat.Builder(getBaseContext());
    mb.addAction(R.drawable.ic_Action, "My Action", btPendingIntent);
    manager.notify(NOTIFICATION_ID, mb.build());
}

BroadcastReceiver class:

public class ButtonReceiver extends BroadcastReceiver {

    @Override
    public void onReceive(Context context, Intent intent) {

        int notificationId = intent.getIntExtra("notificationId", 0);

        NotificationManager manager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
        manager.cancel(notificationId);
    }
}

Solution

  • I believe the issue is in passing in 0 into PendingIntent:

    PendingIntent btPendingIntent = PendingIntent.getActivity(getApplicationContext(), 0, buttonIntent, 0);
    

    I had the same issue until I started passing in the notification id as the 2nd argument; so instead of passing in 0, pass in the id of the notification:

    PendingIntent btPendingIntent = PendingIntent.getActivity(getApplicationContext(), NOTIFICATION_ID, buttonIntent, 0);
    

    After I made that change, I noticed that when clicking on individual notifications (especially notifications in a group) everything worked as intended.