I have a custom notification with a action button:
public class NotificationReceiver extends com.parse.ParsePushBroadcastReceiver {
@Override
public void onPushReceive(Context context, Intent intent) {
...
NotificationActivity notification = new NotificationActivity();
notification.createNotification(context, message, notificationId);
Log.i("tag", "Notification Received!");
}
public class NotificationActivity {
public int notificationId;
public void createNotification(Context context, String message, String studentId, String notificationId){
this.notificationId = Integer.parseInt(notificationId);
// manager
NotificationManager notificationManager =
(NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
// notification
Notification.Builder mBuilder = new Notification.Builder(context);
mBuilder.setContentTitle("My Title");
mBuilder.setContentText(message);
mBuilder.setDefaults(Notification.DEFAULT_VIBRATE);
mBuilder.setAutoCancel(true);
mBuilder.setStyle(new Notification.BigTextStyle()
.bigText(message));
// cancel intent
Intent cancelIntent = new Intent(context, CancelNotification.class);
Bundle extras = new Bundle();
extras.putInt("notification_id", this.notificationId);
cancelIntent.putExtras(extras);
PendingIntent pendingCancelIntent =
PendingIntent.getBroadcast(context, 0, cancelIntent, PendingIntent.FLAG_UPDATE_CURRENT) ;
mBuilder.addAction(R.drawable.notification_close, "Fechar", pendingCancelIntent);
// notify
Notification notification = mBuilder.build();
notificationManager.notify(Integer.parseInt(notificationId), notification);
}
public static class CancelNotification extends BroadcastReceiver {
private int id;
@Override
public void onReceive(Context context, Intent intent) {
id = intent.getIntExtra("notification_id", 1);
NotificationManager notificationManager =
(NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
notificationManager.cancel(id);
}
}
}
I want to cancel the notification which I clicked the action button "Close".
I know that I need the id of the notification to cancel it, but the way I did the code, when I click the "Close" button and create the class CancelNotification which extends BroadCastReceiver I'm getting the notification ID of the last notification, and so, is closing the last notification even if I click on the first notification I created.
What I could be doing wrong?