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. CF912E Prime Gift 数学

    Opposite to Grisha's nice behavior, Oleg, though he has an entire year at his disposal, didn't manag ...

  2. react 中文文档案例一 (倒计时)

    1.函数试组件 import React from 'react'; import ReactDOM from 'react-dom'; function Clock(props){ return( ...

  3. Ubuntu Server 使用 PPA 安装 Java (JDK) 8

    前言 在 Ubuntu Server 中使用 PPA 安装 JDK 相比去 Oracle 官网下载包配置环境变量的好处是,安装方便快捷,还可以 apt-get 更新. 步骤 添加 Java 8 的 P ...

  4. C# 添加vertical 属性上下边框消失问题

    点击这里的曲别针就好了.... 自定义控件主题..... #学习地址: http://www.cnblogs.com/anding/p/4993655.html

  5. Canvas 动态小球重叠效果

    <!doctype html> <html> <head> <meta charset="utf-8"> <title> ...

  6. HDU-Digital Roots(思维+大数字符串模拟)

    The digital root of a positive integer is found by summing the digits of the integer. If the resulti ...

  7. clip-path(css)

    概述 clip-path属性可以防止部分元素通过定义的剪切区域来显示,仅通过显示的特殊区域.剪切区域是被URL定义的路径代替行内或者外部svg,或者定义路线的方法. [注意]  IE浏览器不支持,且低 ...

  8. jquery 初步学习

    首先 jQuery是一个轻量级的 JS框架,核心文件才几十KB 1. jquery 对象 var $variable=jquery对象 var variable = DOM对象 $variable[0 ...

  9. my11_mysql事务隔离

    概述 ************************************************ Mysql有四个事务隔离级别,默认隔离级别为RR,开启一个事务可以使用 START TRANSA ...

  10. NIOGoodDemo

    Java NIO是在jdk1.4开始使用的,它既可以说成“新I/O”,也可以说成非阻塞式I/O.下面是java NIO的工作原理: 1. 由一个专门的线程来处理所有的 IO 事件,并负责分发. 2. ...