Reputation: 271
i want to set an alarms every day of weeks at mighnight this is my code:
int notificationId = getNotificationId(); //it get a random number
Context context = rule.context;
Intent intent = ((Activity) context).getIntent();
long time = getRuleCalendar().getTimeInMillis();
AlarmManager alarmManager = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
PendingIntent pendingIntent = PendingIntent.getBroadcast(context,
notificationId, intent, PendingIntent.FLAG_UPDATE_CURRENT);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
alarmManager.setExactAndAllowWhileIdle(AlarmManager.RTC_WAKEUP, time, pendingIntent);
} else if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
alarmManager.setExact(AlarmManager.RTC_WAKEUP, time,pendingIntent);
} else {
alarmManager.set(AlarmManager.RTC_WAKEUP, time,pendingIntent);
}
public calendar getRuleCalendar(){
Calendar calSet = Calendar.getInstance();
calSet.set(Calendar.DAY_OF_WEEK, calendarDay); //calendarDay change by day of weeks
calSet.set(Calendar.HOUR_OF_DAY, 0);
calSet.set(Calendar.MINUTE, 0);
calSet.set(Calendar.SECOND, 0);
calSet.set(Calendar.MILLISECOND, 1);
return calSet
}
now my problem is that one alarm start immediately (now is after mighnight and it is ok for me i want to check today) but all other alarms start at wrong time. why?
Upvotes: 3
Views: 998
Reputation: 21043
The alarm will only fire immediately if you set the alarm in the past. For example in your case you are setting alarm for 00:00 AM for today which is alway be a past date for today. So you have set set the alarm for next day 00:00 AM . For that just add 1 in Calendar.DAY_OF_YEAR .
public Calendar getRuleCalendar(){
Calendar calSet = Calendar.getInstance();
calSet.set(Calendar.HOUR_OF_DAY, 0);
calSet.set(Calendar.MINUTE, 0);
calSet.set(Calendar.SECOND, 0);
calSet.add(Calendar.DAY_OF_YEAR,1);
calSet.set(Calendar.MILLISECOND, 1);
return calSet;
}
And for setting repeated alarm You have to check out the Documentation.
If you are not aware of background behavior change in Doze Mode starting from android M. Then have a look at Optimizing for Doze and App Standby.
Upvotes: 2