Android – Notification.Builder add action

androidandroid-pendingintentnotificationspush

I'm trying to know which button is pressed so I do this on onReceive

Log.e(TAG, "Clicked " + extras.getInt("ACTION"));

and I always, no matter which button I press, get 3 (ActionEnum.GO_TO_REMINDERS) which is the setContentIntent.

another issue is that the notification is not closed unless I press on the notification buddy, but it's not closed when I press the button.

public void createNotification(Context context, Reminder reminder) {
    // Build notification
    Notification noti = new Notification.Builder(context)
            .setContentTitle(reminder.getDisplayString())
            .setContentText("Pick Action")
            .setSmallIcon(R.drawable.icon_remider)
            .setContentIntent(
                    getPendingAction(context, reminder,
                            ActionEnum.GO_TO_REMINDERS))
            .addAction(R.drawable.icon, "Take",
                    getPendingAction(context, reminder, ActionEnum.TAKE))
            .addAction(R.drawable.icon, "Snooze",
                    getPendingAction(context, reminder, ActionEnum.SNOOZE))
            .addAction(R.drawable.icon, "Remove",
                    getPendingAction(context, reminder, ActionEnum.REMOVE))
            .build();

    NotificationManager notificationManager = (NotificationManager) context
            .getSystemService(Context.NOTIFICATION_SERVICE);
    // hide the notification after its selected
    noti.flags |= Notification.FLAG_AUTO_CANCEL;

    notificationManager.notify(0, noti);

}

public PendingIntent getPendingAction(Context context, Reminder reminder,
        ActionEnum action) {
    // Prepare intent which is triggered if the
    // notification is selected
    Intent intent = new Intent(context, RemindersReceiver.class);
    intent.putExtra("ID", reminder.getIntId());
    intent.putExtra("CLICK", true);
    intent.putExtra("ACTION", action.getValue());
    Log.e(TAG, "set action : " + action.getValue());

    return PendingIntent.getBroadcast(context, 0, intent, 0);
}

Best Answer

Your code in getPendingAction() will always return the same PendingIntent. You are not creating a separate PendingIntent each time you call this method. To ensure that each call creates a separate PendingIntent, you need to make the Intent unique. You can do this by setting the ACTION in the Intent, like this:

intent.setAction(action.name());

To ensure that any old PendingIntents with the same ACTION are overwritten by the latest extras, I would also call getBroadcast() like this:

return PendingIntent.getBroadcast(context, 0, intent,
                    PendingIntent.FLAG_UPDATE_CURRENT);