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
try to use this:
You could use something like this:
I had the same issue as you and I couldn't get it to work. Plus all the examples I could find were also setting a specific date, not only just a time. This should work for you:
Hope this helps you fix your problem!
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 thansetInexactRepeating
)This fixes the issue: