【起航计划 017】2015 起航计划 Android APIDemo的魔鬼步伐 16 App->Alarm->Alarm Controller Alarm事件 PendingIntent Schedule AlarmManager
Alarm Controller演示如何在Android应用中使用Alarm事件,其功能和java.util.Timer ,TimerTask类似。但Alarm可以即使当前应用退出后也可以做到Schedule一个任务在指定的时刻执行。
AlarmManager 用于管理Alarm事件,支持单次执行或重复执行。 和大都数Android服务一样,AlarmManager也是通过getSystemService来获取服务对象:
AlarmManager am = (AlarmManager)getSystemService(ALARM_SERVICE);
与TimerTask对应的任务描述类型为PendingIntent,PendingIntent描述了将要执行的 Intent,PendingIntent没有提供构造函数,需要通过static 函数getActivity(Context, int, Intent, int), getBroadcast(Context, int, Intent, int), getService(Context, int, Intent, int) 来或得想要执行的Activity,Broadcast,Service描述。
本例中是取得对Broadcast OneShotAlarm 和RepeatingAlarm的描述,分别对应于单次执行时执行的Broadcast事件和多次执行时Broadcast事件,它们在 AndroidManifest.xml定义为Broadcast Receiver:
<receiver android:name=”.app.OneShotAlarm” android:process=”:remote” />
<receiver android:name=”.app.RepeatingAlarm” android:process=”:remote” />
Schedule单次Alarm事件代码如下:
// When the alarm goes off, we want to broadcast an Intent to our
// BroadcastReceiver. Here we make an Intent with an explicit class
// name to have our own receiver (which has been published in
// AndroidManifest.xml) instantiated and called, and then create an
// IntentSender to have the intent executed as a broadcast.
Intent intent = new Intent(AlarmController.this, OneShotAlarm.class);
PendingIntent sender = PendingIntent.getBroadcast(AlarmController.this,
0, intent, 0); // We want the alarm to go off 30 seconds from now.
Calendar calendar = Calendar.getInstance();
calendar.setTimeInMillis(System.currentTimeMillis());
calendar.add(Calendar.SECOND, 30); // Schedule the alarm!
AlarmManager am = (AlarmManager)getSystemService(ALARM_SERVICE);
am.set(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(), sender);
其中sender为对发给Broadcast Receiver OneShotAlarm的Intent的描述,当到达指定的时间(例子中为30秒),AlarmManager将给OneShotAlarm发出一个 Broadcast Intent,OneShotAlarm接到后,将使用Toast在屏幕上显示一个消息。 如果你多次点击“One Shot Alarm”并不会Schedule多个Alarm事件,这是因为Schedule同一个Sender对象,后一次将取消上此Scheduled的事件。

Schedule一个重复事件代码如下:
// When the alarm goes off, we want to broadcast an Intent to our
// BroadcastReceiver. Here we make an Intent with an explicit class
// name to have our own receiver (which has been published in
// AndroidManifest.xml) instantiated and called, and then create an
// IntentSender to have the intent executed as a broadcast.
// Note that unlike above, this IntentSender is configured to
// allow itself to be sent multiple times.
Intent intent = new Intent(AlarmController.this, RepeatingAlarm.class);
PendingIntent sender = PendingIntent.getBroadcast(AlarmController.this,
0, intent, 0); // We want the alarm to go off 30 seconds from now.
long firstTime = SystemClock.elapsedRealtime();
firstTime += 15*1000; // Schedule the alarm!
AlarmManager am = (AlarmManager)getSystemService(ALARM_SERVICE);
am.setRepeating(AlarmManager.ELAPSED_REALTIME_WAKEUP,
firstTime, 15*1000, sender);
上述代码每15秒给RepeatingAlarm 发出一个Broadcast事件,RepeatingAlarm接受到后,也在屏幕上显示一个消息。

对于与Schedule的事件,单次或多次的,都可以调用AlarmManager 的cancel方法取消Schedule的Alarm事件,下面代码取消多次Alarm事件。
// Create the same intent, and thus a matching IntentSender, for
// the one that was scheduled.
Intent intent = new Intent(AlarmController.this, RepeatingAlarm.class);
PendingIntent sender = PendingIntent.getBroadcast(AlarmController.this,
0, intent, 0); // And cancel the alarm.
AlarmManager am = (AlarmManager)getSystemService(ALARM_SERVICE);
am.cancel(sender);
注:如果你没有Cancel这个多次Alarm事件,每隔15秒屏幕上都会显示一个消息,即使你退出这个例子或是启动其它应用,直到Reboot之后才中止。
【起航计划 017】2015 起航计划 Android APIDemo的魔鬼步伐 16 App->Alarm->Alarm Controller Alarm事件 PendingIntent Schedule AlarmManager的更多相关文章
- 【起航计划 002】2015 起航计划 Android APIDemo的魔鬼步伐 01
本文链接:[起航计划 002]2015 起航计划 Android APIDemo的魔鬼步伐 01 参考链接:http://blog.csdn.net/column/details/mapdigitap ...
- 【起航计划 037】2015 起航计划 Android APIDemo的魔鬼步伐 36 App->Service->Remote Service Binding AIDL实现不同进程间调用服务接口 kill 进程
本例和下个例子Remote Service Controller 涉及到的文件有RemoteService.java ,IRemoteService.aidl, IRemoteServiceCallb ...
- 【起航计划 031】2015 起航计划 Android APIDemo的魔鬼步伐 30 App->Preferences->Advanced preferences 自定义preference OnPreferenceChangeListener
前篇文章Android ApiDemo示例解析(31):App->Preferences->Launching preferences 中用到了Advanced preferences 中 ...
- 【起航计划 027】2015 起航计划 Android APIDemo的魔鬼步伐 26 App->Preferences->Preferences from XML 偏好设置界面
我们在前面的例子Android ApiDemo示例解析(9):App->Activity->Persistent State 介绍了可以使用Shared Preferences来存储一些状 ...
- 【起航计划 020】2015 起航计划 Android APIDemo的魔鬼步伐 19 App->Dialog Dialog样式
这个例子的主Activity定义在AlertDialogSamples.java 主要用来介绍类AlertDialog的用法,AlertDialog提供的功能是多样的: 显示消息给用户,并可提供一到三 ...
- 【起航计划 012】2015 起航计划 Android APIDemo的魔鬼步伐 11 App->Activity->Save & Restore State onSaveInstanceState onRestoreInstanceState
Save & Restore State与之前的例子Android ApiDemo示例解析(9):App->Activity->Persistent State 实现的UI类似,但 ...
- 【起航计划 003】2015 起航计划 Android APIDemo的魔鬼步伐 02 SimpleAdapter,ListActivity,PackageManager参考
01 API Demos ApiDemos 详细介绍了Android平台主要的 API,android 5.0主要包括下图几个大类,涵盖了数百api示例:
- 【起航计划 035】2015 起航计划 Android APIDemo的魔鬼步伐 34 App->Service->Local Service Controller
Local Service Controller 是将LocalService当作“Started”Service来使用,相对于”Bound” Service 来说,这种模式用法要简单得多,Local ...
- 【起航计划 034】2015 起航计划 Android APIDemo的魔鬼步伐 33 App->Service->Local Service Binding 绑定服务 ServiceConnection Binder
本例和下列Local Service Controller 的Activity代码都定义在LocalServiceActivities.Java 中,作为LocalServiceActivities ...
随机推荐
- 当我们谈论CloudTable时究竟在谈论什么?
表格存储服务(CloudTable Service,简称CloudTable)是基于Apache HBase提供的分布式.可伸缩.全托管的毫秒级NoSQL数据存储服务.它提供了毫秒级的随机读写能力,适 ...
- django 访问静态资源
urlpatterns = patterns('', url(r'^$', views.show, name='index'), url(r'^static/(?P<path>.*)', ...
- Codeforces 237E
没啥好说的 #include<iostream> #include<algorithm> #include<cstdio> #include<cstring& ...
- SHA_1计算消息摘要
/** * SHA_1计算消息摘要 * @param bytes 待计算数据 * @return */ public static String SHA_1(byte[] bytes) { Strin ...
- redis 学习字符类型 hash
> HSET userinfo1 username "king" (integer) > HSET userinfo1 passowor " (integer ...
- django ORM 连表查询
db_index=True 如果设置该字段就可以设置索引 auto_now_add 代表设置创建时候的时间 auto_now 每次更新数据记录时会更新该字段 to_field 设置要关联表的字 ...
- 1.3 guessing game
创建项目 [root@itoracle test]# cargo new guessing_game Created binary (application) `guessing_game` pack ...
- mysql 模拟一个自增序列
文章出处:https://sdu0rj.axshare.com/%E4%BA%8C%E7%BA%A7%E5%AE%A2%E6%88%B7%E7%AE%A1%E7%90%86.html mysql没有像 ...
- Kafka Intro - Configuration
#Notes: /opt/kafka/config/zookeeper.properties sample # the directory where the snapshot is stored.d ...
- PlayMaker 设置颜色 Set Materia lColor
1. 指定一个游戏对象,Color处设为红色,执行这个行为后就把游戏对象的材质变为了红色: 2. Color也可以使用一个弄好的Color类型的变量,如下图:Color处用了一个提前设置好的变量