码迷,mamicode.com
首页 > 移动开发 > 详细

Android 开发工具类 17_setAlarm

时间:2015-05-28 22:54:14      阅读:238      评论:0      收藏:0      [点我收藏+]

标签:

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 }

 

Android 开发工具类 17_setAlarm

标签:

原文地址:http://www.cnblogs.com/renzimu/p/4536958.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!