Alarm 是在应用程序生命周期之外设置的,所以它们十分适合于调度定时更新或者数据查询,从而避免了在后台持续运行 Service。但触发 Alarm 时,就会广播指定的 Pending Intent。
Alarm 类型:
1、RTC_WAKEUP:在指定的时间唤醒设备,并激活 Pending Intent。
2、RTC:在指定的时间点激活 Pending Intent,但是不会唤醒设备。
3、ELAPSED_REALTIME:根据设备启动之后经过的时间激活 Pending Intent,但是不会唤醒设备。经过的时间包含设备休眠的所有时间。
4、ELAPSED_REALTIME_WAKEUP:在设备启动并经过指定的时间之后唤醒设备和激活 Pending Intent。
private void setAlarm() {
/**
* Listing 9-16: Creating a waking Alarm that triggers in 10 seconds
*/
// Get a reference to the Alarm Manager
AlarmManager alarmManager =
(AlarmManager)getSystemService(Context.ALARM_SERVICE); // Set the alarm to wake the device if sleeping.
int alarmType = AlarmManager.ELAPSED_REALTIME_WAKEUP; // Trigger the device in 10 seconds.
long timeOrLengthofWait = 10000; // Create a Pending Intent that will broadcast and action
String ALARM_ACTION = "ALARM_ACTION";
Intent intentToFire = new Intent(ALARM_ACTION);
PendingIntent alarmIntent = PendingIntent.getBroadcast(this, 0,
intentToFire, 0); // Set the alarm
alarmManager.set(alarmType, timeOrLengthofWait, alarmIntent); /**
* Listing 9-17: Canceling an Alarm
*/
alarmManager.cancel(alarmIntent);
} private void setInexactRepeatingAlarm() {
/**
* Listing 9-18: Setting an inexact repeating alarm
*/
//Get a reference to the Alarm Manager
AlarmManager alarmManager =
(AlarmManager)getSystemService(Context.ALARM_SERVICE); //Set the alarm to wake the device if sleeping.
int alarmType = AlarmManager.ELAPSED_REALTIME_WAKEUP; //Schedule the alarm to repeat every half hour.
long timeOrLengthofWait = AlarmManager.INTERVAL_HALF_HOUR; //Create a Pending Intent that will broadcast and action
String ALARM_ACTION = "ALARM_ACTION";
Intent intentToFire = new Intent(ALARM_ACTION);
PendingIntent alarmIntent = PendingIntent.getBroadcast(this, 0,
intentToFire, 0); //Wake up the device to fire an alarm in half an hour, and every
//half-hour after that.
alarmManager.setInexactRepeating(alarmType,
timeOrLengthofWait,
timeOrLengthofWait,
alarmIntent);
}
}