I'm having trouble working with the AlarmManager
. I want to run AlarmManager
using Calendar at a specific time.
But the calendar doesn't work and AlarmManager
always runs regardless of the time taken from the calendar.
AlarmManager mAlarmManger = (AlarmManager) Objects.requireNonNull(activity).getSystemService(view.getContext().ALARM_SERVICE);
Intent intent = new Intent(activity, MyReceiver.class);
PendingIntent pendingIntent = PendingIntent.getBroadcast(activity, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT);
Calendar calendar = Calendar.getInstance();
calendar.set(Calendar.WEEK_OF_YEAR, Calendar.MONTH , Calendar.DAY_OF_MONTH, 11, 55, 0);
calendar.set(Calendar.AM_PM, Calendar.AM);
if(android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.O){
mAlarmManger.setExactAndAllowWhileIdle(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(), pendingIntent);
}
else{
mAlarmManger.set(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(), pendingIntent);
}
AlarmManager should run at 11:55 AM everyDay, but will run as soon as the app opens.
Calendar calendar = Calendar.getInstance();
calendar.set(Calendar.HOUR_OF_DAY, 11);
calendar.set(Calendar.MINUTE, 30);
calendar.set(Calendar.SECOND, 0);
if (calendar.getTimeInMillis() > System.currentTimeMillis()) {
Intent intent = new Intent(MainActivity.this, AlarmReceiver.class);
pendingIntent = PendingIntent.getBroadcast(MainActivity.this, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT);
AlarmManager am = (AlarmManager) MainActivity.this.getSystemService(MainActivity.this.ALARM_SERVICE);
am.setInexactRepeating(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(), 24 * 60 * 60 * 1000, pendingIntent); //Repeat every 24 h
}
Try this..