Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Set Repeated alarm at specific time every day

I try to use alarm manager to run alarm at specific time every day. I am using this code

Intent intent = new Intent(AlarmSettings.this, AlarmService.class);
                        intent.putExtra("i", i);
PendingIntent mAlarmSender = PendingIntent.getService(AlarmSettings.this, Id, intent, 0);

AlarmManager am = (AlarmManager)getSystemService(ALARM_SERVICE);

am.setRepeating(AlarmManager.RTC_WAKEUP, cal.getTimeInMillis(),Calendar.getInstance().getTimeInMillis()+(24*60*60*1000), mAlarmSender);}

the problem was in if cal.getTimeInMillis() value is in the past the alarm run immediately, i do not know why, and when cal.getTimeInMillis() value is in the future it runs correctly at its time.

I need to make it run at specific time every day.

like image 533
Yasser-Farag Avatar asked Dec 12 '22 08:12

Yasser-Farag


1 Answers

// every day at 9 am
Calendar calendar = Calendar.getInstance();

// if it's after or equal 9 am schedule for next day
if (Calendar.getInstance().get(Calendar.HOUR_OF_DAY) >= 9) {
    calendar.add(Calendar.DAY_OF_YEAR, 1); // add, not set!
}
calendar.set(Calendar.HOUR_OF_DAY, 9);
calendar.set(Calendar.MINUTE, 0);
calendar.set(Calendar.SECOND, 0);

AlarmManager alarmManager = (AlarmManager) getSystemService(ALARM_SERVICE);

alarmManager.setInexactRepeating(AlarmManager.RTC, calendar.getTimeInMillis(),
            AlarmManager.INTERVAL_DAY, pi);

// alarmManager.setRepeating(AlarmManager.RTC, calendar.getTimeInMillis(),
// AlarmManager.INTERVAL_DAY, pi);
like image 50
Rikin Patel Avatar answered Jan 08 '23 11:01

Rikin Patel