Android 开发工具类 17_setAlarm

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。

 1 private void setAlarm() {
 2     /**
 3      * Listing 9-16: Creating a waking Alarm that triggers in 10 seconds
 4      */
 5     // Get a reference to the Alarm Manager
 6     AlarmManager alarmManager = 
 7      (AlarmManager)getSystemService(Context.ALARM_SERVICE);
 8   
 9     // Set the alarm to wake the device if sleeping.
10     int alarmType = AlarmManager.ELAPSED_REALTIME_WAKEUP;
11   
12     // Trigger the device in 10 seconds.
13     long timeOrLengthofWait = 10000;
14   
15     // Create a Pending Intent that will broadcast and action
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     // Set the alarm
22     alarmManager.set(alarmType, timeOrLengthofWait, alarmIntent);
23     
24     /**
25      * Listing 9-17: Canceling an Alarm
26      */
27     alarmManager.cancel(alarmIntent);
28   }
29   
30   private void setInexactRepeatingAlarm() {
31     /**
32      * Listing 9-18: Setting an inexact repeating alarm
33      */
34     //Get a reference to the Alarm Manager
35     AlarmManager alarmManager = 
36     (AlarmManager)getSystemService(Context.ALARM_SERVICE);
37     
38     //Set the alarm to wake the device if sleeping.
39     int alarmType = AlarmManager.ELAPSED_REALTIME_WAKEUP;
40     
41     //Schedule the alarm to repeat every half hour.
42     long timeOrLengthofWait = AlarmManager.INTERVAL_HALF_HOUR;
43     
44     //Create a Pending Intent that will broadcast and action
45     String ALARM_ACTION = "ALARM_ACTION";
46     Intent intentToFire = new Intent(ALARM_ACTION);
47     PendingIntent alarmIntent = PendingIntent.getBroadcast(this, 0,
48      intentToFire, 0);
49     
50     //Wake up the device to fire an alarm in half an hour, and every 
51     //half-hour after that.
52     alarmManager.setInexactRepeating(alarmType,
53                               timeOrLengthofWait, 
54                               timeOrLengthofWait,
55                               alarmIntent);
56   }
57 }

 

郑重声明:本站内容如果来自互联网及其他传播媒体,其版权均属原媒体及文章作者所有。转载目的在于传递更多信息及用于网络分享,并不代表本站赞同其观点和对其真实性负责,也不构成任何其他建议。