创建只激活一次的Alarm,可使用Set方法,给它指定一个Alarm类型、触发时间和一个要激活的pending Intent。
4种Alarm类型:
● RTC_WAKEUP:指定时间唤醒设备,并激活Pending intent
● RTC:指定时间点激活Pending ,但不会唤醒设备
● ELAPSED_REALTIME:设备启动之后经过的时间激活Pending intent,但不唤醒设备
● ELAPSED_REALTIME_WAKEUP:在设备启动并经过指定的时间之后唤醒设备和激活Pending Intent
1: private void setAlarm() {
2: /**
3: * Listing 9-16: 创建一个唤醒 Alarm 它在10秒钟后触发
4: */
5: // 获取一个 Alarm Manager 引用
6: AlarmManager alarmManager =
7: (AlarmManager)getSystemService(Context.ALARM_SERVICE);
8:
9: // 如设备处于休眠状态,设置alarm来唤醒设备
10: int alarmType = AlarmManager.ELAPSED_REALTIME_WAKEUP;
11:
12: // 10秒钟后触发设备
13: long timeOrLengthofWait = 10000;
14:
15: // 创建广播和操作的Pending Intent
16: String ALARM_ACTION = "ALARM_ACTION";
17: Intent intentToFire = new Intent(ALARM_ACTION);
18: PendingIntent alarmIntent = PendingIntent.getBroadcast(this, 0,
19: intentToFire, 0);
20:
21: // 设置Alarm Set the alarm
22: alarmManager.set(alarmType, timeOrLengthofWait, alarmIntent);