Set Repeating Alarm Every Day at Specific time In Android
alarmmanager, android, calendar
Solution
The alarm will only fire immediately if you set the alarm in the past. E.g. it is now 10:00h and you want to set an alarm every day at 09:00. To avoid this, you have to look what time it is now, and shift the alarm 1 day if that is the case... This allows you to use the `setRepeating` method (which is more precise than `setInexactRepeating`)
This fixes the issue:
Calendar calendar = Calendar.getInstance();
calendar.setTimeInMillis(System.currentTimeMillis());
calendar.set(Calendar.HOUR_OF_DAY, 00);
calendar.set(Calendar.MINUTE, 00);
if(Calendar.getInstance().after(calendar)){
// Move to tomorrow
calendar.add(Calendar.DATE, 1);
}
//... continue like before by setting the alarm
Problem
I am using Alarm manager to run alarm at specific time every day. Below is the code ``` Calendar calendar = Calendar.getInstance(); calendar.setTimeInMillis(System.currentTimeMillis()); calendar.set(Calendar.HOUR_OF_DAY, 00); calendar.set(Calendar.MINUTE, 00); AlarmManager alarmManager = (AlarmManager) getSystemService(ALARM_SERVICE); Intent intent = new Intent(this, OnAlarmReceive.class); PendingIntent pendingIntent =PendingIntent.getBroadcast(this.getApplicationContext(), 0, intent,PendingIntent.FLAG_UPDATE_CURRENT); alarmManager.setRepeating(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(), 24*60*60*1000, pendingIntent); ``` I am Setting alarm at 12AM every day. And Below is the code for BroadCastReciever ``` @Override public void onReceive(Context context, Intent intent) { System.out.println("Time is 12 Am"); Toast.makeText(context, "Alarm Triggered", Toast.LENGTH_LONG).show(); } ``` Problem in this code is Alarm is Triggered As soon as i Run the Application Irrespective of time. Any help will be Appreciated. Thank You