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的更多相关文章

  1. 【起航计划 002】2015 起航计划 Android APIDemo的魔鬼步伐 01

    本文链接:[起航计划 002]2015 起航计划 Android APIDemo的魔鬼步伐 01 参考链接:http://blog.csdn.net/column/details/mapdigitap ...

  2. 【起航计划 037】2015 起航计划 Android APIDemo的魔鬼步伐 36 App->Service->Remote Service Binding AIDL实现不同进程间调用服务接口 kill 进程

    本例和下个例子Remote Service Controller 涉及到的文件有RemoteService.java ,IRemoteService.aidl, IRemoteServiceCallb ...

  3. 【起航计划 031】2015 起航计划 Android APIDemo的魔鬼步伐 30 App->Preferences->Advanced preferences 自定义preference OnPreferenceChangeListener

    前篇文章Android ApiDemo示例解析(31):App->Preferences->Launching preferences 中用到了Advanced preferences 中 ...

  4. 【起航计划 027】2015 起航计划 Android APIDemo的魔鬼步伐 26 App->Preferences->Preferences from XML 偏好设置界面

    我们在前面的例子Android ApiDemo示例解析(9):App->Activity->Persistent State 介绍了可以使用Shared Preferences来存储一些状 ...

  5. 【起航计划 020】2015 起航计划 Android APIDemo的魔鬼步伐 19 App->Dialog Dialog样式

    这个例子的主Activity定义在AlertDialogSamples.java 主要用来介绍类AlertDialog的用法,AlertDialog提供的功能是多样的: 显示消息给用户,并可提供一到三 ...

  6. 【起航计划 012】2015 起航计划 Android APIDemo的魔鬼步伐 11 App->Activity->Save & Restore State onSaveInstanceState onRestoreInstanceState

    Save & Restore State与之前的例子Android ApiDemo示例解析(9):App->Activity->Persistent State 实现的UI类似,但 ...

  7. 【起航计划 003】2015 起航计划 Android APIDemo的魔鬼步伐 02 SimpleAdapter,ListActivity,PackageManager参考

    01 API Demos ApiDemos 详细介绍了Android平台主要的 API,android 5.0主要包括下图几个大类,涵盖了数百api示例:

  8. 【起航计划 035】2015 起航计划 Android APIDemo的魔鬼步伐 34 App->Service->Local Service Controller

    Local Service Controller 是将LocalService当作“Started”Service来使用,相对于”Bound” Service 来说,这种模式用法要简单得多,Local ...

  9. 【起航计划 034】2015 起航计划 Android APIDemo的魔鬼步伐 33 App->Service->Local Service Binding 绑定服务 ServiceConnection Binder

    本例和下列Local Service Controller 的Activity代码都定义在LocalServiceActivities.Java 中,作为LocalServiceActivities ...

随机推荐

  1. kuangbin专题十六 KMP&&扩展KMP HDU3336 Count the string

    It is well known that AekdyCoin is good at string problems as well as number theory problems. When g ...

  2. 模拟使用zookeeper实现master选举

    1.模拟选举机器类 package com.karat.cn.zookeeperAchieveLock.zkclient; import java.io.Serializable; /** * 选举的 ...

  3. ie浏览器(Internet Explorer)不播放背景音乐

    这里就不说bgsound了,支持格式较少 一个网站要加背景音乐,好些年没加背景音乐了,用embed标签把背景音乐加上了,Mozilla Firefox,Google Chrome,Safari都正常, ...

  4. 读经典——《CLR via C#》(Jeffrey Richter著) 笔记_基元类型(三)

    [checked 和 unchecked 基元类型操作] 1.第一种使用方式 UInt32 invalid = )); //OK,不会抛异常 Byte b = ; b = ));//抛出Overflo ...

  5. 浅谈ORM操作

    2. ORM(对象关系映射) 1. 映射的关系 DB ORM 数据表 <--> 类 数据行 <--> 对象 字段 <--> 属性 2. Django项目使用MySQ ...

  6. my09_mysql指定时间点恢复之binlog start-position

    场景描述 ********************************************* 在远程服务器做的全备并已经恢复,同时使用binlog server备份binlog 之后,删除了库 ...

  7. java——数组栈 ArrayStack

    栈的应用: undo操作-编辑器 系统调用栈-操作系统 括号匹配-编译器 以下是动态数组实现的数组栈: 定义动态数组: package Date_pacage; public class Array& ...

  8. 转 python 随机走动的模拟

    https://blog.csdn.net/python2014/article/details/21231971 麻省理工的随机走动模块,还不错,三天搞懂了,不过懂得不彻底.   记录下修改的代码 ...

  9. @RequestParam详解以及加与不加的区别

    以前写controller层的时候都是默认带上 @RequestParam 的, 今天发现不加@RequestParam 也能接收到参数 下面我们来区分一下加与不加的区别 这里有两种写法 @Reque ...

  10. Jquery ValidationEngine 修改验证提示框的位置

    <!doctype html> <html lang="en"> <head> <meta charset="UTF-8&quo ...