问题
In my app, I set an alarm
AlarmManager alarmMgr = (AlarmManager)context.getSystemService(Context.ALARM_SERVICE);
...
PendingIntent pendingIntent = PendingIntent.getBroadcast(context, id, intent, PendingIntent.FLAG_UPDATE_CURRENT);
...
alarmMgr.set(AlarmManager.RTC_WAKEUP, time.getTimeInMillis(), pendingIntent);
It works fine unless I turn off and turn on the phone.
To be more specific, let's say at 10:20, I set an alarm to 10:22 and I turn off and turn on the phone at 10:21, alarm won't work.
What might be the problem? Is that a broadcast issue of the pendingIntent there or should I set some flags of the alarmManager object for it to work in such conditions?
回答1:
The documentation about the AlarmManager says that :
Registered alarms are retained while the device is asleep (and can optionally wake the device up if they go off during that time), but will be cleared if it is turned off and rebooted.
It seems that the AlarmClock included by default by Android does work even after a reboot.
On way to keep your alarms working after a reboot, is to start your application on boot completed and set up all the alams again with the AlarmManager. (In fact you may want to just setup your alarms using a Broadcast, not start your app)
Here is a StackOverflow question dealing about lunching an app on startup.
You wan also check out how the default AlarmClock does this by reading from the source. You can read and download it from here
来源:https://stackoverflow.com/questions/8774030/alarmmanager-object-after-turning-off-and-on-the-phone