In my app I want to show as many daily notifications as user wants (it's sort of a medical reminder). User also sets time of the new notification. But my app currently shows only one, latest notification. Could you help me solve this problem?
My code for creating new notification (setHour
etc. are previously set by the user):
Calendar calendar = Calendar.getInstance();
calendar.set(Calendar.HOUR_OF_DAY, setHour);
calendar.set(Calendar.MINUTE, setMinute);
calendar.set(Calendar.SECOND, 0);
Intent intent1 = new Intent(ReminderActivity.this, AlarmReceiver.class);
PendingIntent pendingIntent = PendingIntent.getBroadcast(ReminderActivity.this, MID,intent1, 0);
AlarmManager am = (AlarmManager) ReminderActivity.this.getSystemService(ReminderActivity.this.ALARM_SERVICE);
am.setRepeating(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(), AlarmManager.INTERVAL_DAY, pendingIntent);
And my AlarmReceiver
:
public class AlarmReceiver extends BroadcastReceiver {
public static int MID = 0;
private static final String CHANNEL_ID = "this.is.my.channelId";
@Override
public void onReceive(Context context, Intent intent) {
Intent notificationIntent = new Intent(context, MainActivity.class);
TaskStackBuilder stackBuilder = TaskStackBuilder.create(context);
stackBuilder.addParentStack(MainActivity.class);
stackBuilder.addNextIntent(notificationIntent);
PendingIntent pendingIntent = stackBuilder.getPendingIntent(MID, 0);
Notification.Builder builder = new Notification.Builder(context);
Notification notification = builder.setContentTitle("Notification")
.setContentText("New Notification")
.setTicker("New Message Alert!")
.setSmallIcon(R.mipmap.ic_launcher)
.setVibrate(new long[]{1000, 1000, 1000, 1000, 1000})
.setContentIntent(pendingIntent).build();
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
builder.setChannelId(CHANNEL_ID);
}
NotificationManager notificationManager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
//below creating notification channel, because of androids latest update, O is Oreo
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
NotificationChannel channel = new NotificationChannel(
CHANNEL_ID,
"NotificationDemo",
NotificationManager.IMPORTANCE_DEFAULT
);
notificationManager.createNotificationChannel(channel);
}
notificationManager.notify(MID, notification);
MID++;
}
}