Search code examples
androidnotificationsalarmmanagerandroid-pendingintent

the new notification cancel the old one


in my application the user has to add multiple notifications , but my problem is when the user add the new notification the old one deleted or canceled .And I think it's from the pendingIntent , what the appropriate flag should i use ?

here is some of my code :

Calendar calendar = Calendar.getInstance();
    Intent intent;
    PendingIntent pendingIntent;
    AlarmManager alarmManager;
    long futureInMillis;
    switch (type) {
        case SCHEDULE_BY_DAYS:
            intent = new Intent(this, NotificationReceiver.class);
            intent.putExtra(NotificationReceiver.NOTIFICATION_ID, 1);
            intent.putExtra(NotificationReceiver.NOTIFICATION, getNotification("WAKEP UP days !!"));
            pendingIntent = PendingIntent.getBroadcast(this, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT);
            alarmManager = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
            alarmManager.set(AlarmManager.ELAPSED_REALTIME_WAKEUP, calendar.getTimeInMillis(), pendingIntent);
            break;
        case SCHEDULE_BY_HOURS:

            futureInMillis = SystemClock.elapsedRealtime() + (value * 600000);
            intent = new Intent(this, NotificationReceiver.class);
            intent.putExtra(NotificationReceiver.NOTIFICATION_ID, 1);
            intent.putExtra(NotificationReceiver.NOTIFICATION, getNotification("WAKEP UP hours"));
            pendingIntent = PendingIntent.getBroadcast(this, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT);

            alarmManager = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
            alarmManager.set(AlarmManager.ELAPSED_REALTIME_WAKEUP, futureInMillis, pendingIntent);
            break;

Solution

  • If you specify a different requestCode for each PendingIntent notifications won't cancel each other.

    PendingIntent.getBroadcast(this, unique_code, intent, PendingIntent.FLAG_UPDATE_CURRENT);

    Edit

    int uniqueCode = sharedPreferences.getInt("unique_code",0) + 1;
    sharedPreferences.edit().putInt("unique_code",uniqueCode).apply()