Reputation: 1084
I need to run a service each night at midnight. I would like to use the AlarmManager to do this.
Can you give me some guidance of how to make it work correctly?
alarmManager = (AlarmManager)context.getSystemService(Context.ALARM_SERVICE);
alarmManager.setInexactRepeating(AlarmManager.ELAPSED_REALTIME, System.currentTimeMillis(), AlarmManager.INTERNAL_DAY, serviceIntent);
Perhaps I need to use a Calendar object to specify the time? Thanks for any help!
Upvotes: 3
Views: 6446
Reputation: 4168
If you want your code to run specifically midnight, don't use "setInexactRepeating". In fact, you need: alarmManager.setRepeating(RTC_WAKEUP, ...)
, and then use Calendar
to calculate the next midnight you want to run at.
If your need to wake up at midnight is dependent on user activity such that there's no need to wake up the phone exactly at midnight, just that the action should be run first if the user uses the phone after midnight, you can change RTC_WAKEUP
to just RTC
. Although, the battery effects of waking up exactly at midnight with RTC_WAKEUP
should be neglible, so it's probably simpler to just force the wakeup.
Upvotes: 0
Reputation: 1006614
setInexactRepeating()
, as the name suggests, is inexact. Bear in mind that it might run somewhat before or after midnight.
To determine when midnight is, use a Calendar
object. Then call getDate()
to get a Date
and getTime()
on the Date
to get the proper millisecond value for your setInexactRepeating()
call.
Upvotes: 6