I have this code
Calendar c = new GregorianCalendar();
c.add(Calendar.DAY_OF_YEAR, 1);
c.set(Calendar.HOUR_OF_DAY, 23);
c.set(Calendar.MINUTE, 22);
c.set(Calendar.SECOND, 0);
c.set(Calendar.MILLISECOND, 0);
// We want the alarm to go off 30 seconds from now.
long firstTime = SystemClock.elapsedRealtime();
firstTime += 30*1000;
long a=c.getTimeInMillis();
// Schedule the alarm!
AlarmManager am = (AlarmManager)ctx.getSystemService(Context.ALARM_SERVICE);
am.setRepeating(AlarmManager.ELAPSED_REALTIME_WAKEUP,
c.getTimeInMillis(), 1*60*60*1000, sender);
It is not executed at 23:22h
What I am doing wrong? I noticed firstTime and c.getTimeInMillis() differs a lot in size and length. When I use firstTime, so when set to 30 seconds, the alarm is executed well.
What is this permission? The new exact alarm permission ( SCHEDULE_EXACT_ALARM ) was created to save system resources. Alarms that must be executed in an exact time may be triggered when the phone is on power-saving mode or Doze, making the app consumes more battery than it should.
The alarm is an Intent broadcast that goes to a broadcast receiver that you registered with Context. registerReceiver(BroadcastReceiver, IntentFilter) or through the <receiver> tag in an AndroidManifest. xml file. Alarm intents are delivered with a data extra of type int called Intent.
You are using the AlarmManager.ELAPSED_REALTIME_WAKEUP
flag, but you are using a Calendar object. These two things don't go together.
You need to use AlarmManager.RTC or AlarmManager.RTC_WAKEUP
if you are specifying the alarm time using a Calendar or Date object (milliseconds since 1970).
You use AlarmManager.ELAPSED_REALTIME
or AlarmManager.ELAPSED_REALTIME_WAKEUP
when you are specifying the alarm time via SystemClock.elapsedRealtime()
(milliseconds since the phone booted).
I had success with the following code, if you only want to set the alarm for the next occurance of hh:mm
Calendar cal = new GregorianCalendar();
cal.setTimeInMillis(System.currentTimeMillis());
cal.set(Calendar.HOUR_OF_DAY, 22);
cal.set(Calendar.MINUTE, 19);
cal.set(Calendar.SECOND, 0);
cal.set(Calendar.MILLISECOND, 0);
//check if we want to wake up tomorrow
if (System.currentTimeMillis() > cal.getTimeInMillis()){
cal.setTimeInMillis(cal.getTimeInMillis()+ 24*60*60*1000);// Okay, then tomorrow ...
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With