Alarm are set up outside the application life cycle, so they are ideal for scheduling scheduled updates or data queries, thus avoiding running the Service continuously in the background. However, when Alarm is triggered, the specified Pending Intent is broadcast.
Alarm Type:
1. Rtc_wakeup: Wakes the device at the specified time and activates the Pending Intent.
2. RTC: Activates the Pending Intent at a specified point in time, but does not wake the device.
3. Elapsed_realtime: Activates Pending Intent according to the time elapsed after the device is started, but does not wake the device. Elapsed time contains all the time that the device sleeps.
4. Elapsed_realtime_wakeup: Wakes the device and activates the Pending Intent after the device has been started and after a specified time.
1 Private voidSetalarm () {2 /**3 * Listing 9-16:creating a waking Alarm that triggers in seconds4 */5 //Get A reference to the Alarm Manager6Alarmmanager Alarmmanager =7 (Alarmmanager) Getsystemservice (context.alarm_service);8 9 //Set the alarm to wake the device if sleeping.Ten intAlarmtype =Alarmmanager.elapsed_realtime_wakeup; One A //Trigger the device in ten seconds. - LongTimeorlengthofwait = 10000; - the //Create a Pending Intent that'll broadcast and action -String alarm_action = "Alarm_action"; -Intent Intenttofire =NewIntent (alarm_action); -Pendingintent alarmintent = Pendingintent.getbroadcast ( This, 0, +Intenttofire, 0); - + //Set the alarm A Alarmmanager.set (Alarmtype, timeorlengthofwait, alarmintent); at - /** - * Listing 9-17:canceling an Alarm - */ - Alarmmanager.cancel (alarmintent); - } in - Private voidSetinexactrepeatingalarm () { to /** + * Listing 9-18:setting an inexact repeating alarm - */ the //Get A reference to the Alarm Manager *Alarmmanager Alarmmanager = $ (Alarmmanager) Getsystemservice (context.alarm_service);Panax Notoginseng - //Set the alarm to wake the device if sleeping. the intAlarmtype =Alarmmanager.elapsed_realtime_wakeup; + A //Schedule the alarm to repeat every half hour. the LongTimeorlengthofwait =Alarmmanager.interval_half_hour; + - //Create a Pending Intent that'll broadcast and action $String alarm_action = "Alarm_action"; $Intent Intenttofire =NewIntent (alarm_action); -Pendingintent alarmintent = Pendingintent.getbroadcast ( This, 0, -Intenttofire, 0); the - //Wake up the device to fire a alarm in half an hour, and everyWuyi //half-hour after. the alarmmanager.setinexactrepeating (Alarmtype, - timeorlengthofwait, Wu timeorlengthofwait, - alarmintent); About } $}
Android development tool Class 17_setalarm