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. 最短路【洛谷P1606】 [USACO07FEB]荷叶塘Lilypad Pond

    P1606 [USACO07FEB]荷叶塘Lilypad Pond 为了让奶牛们娱乐和锻炼,农夫约翰建造了一个美丽的池塘.这个长方形的池子被分成了M行N列个方格(1≤M,N≤30).一些格子是坚固得令 ...

  2. C++_引用变量探究

    什么是引用 引用变量是已定义变量的别名. 如何定义引用变量: int rats; int & rodents = rats; 其中&不失地址运算符,而是类型标识符的一部分.就行声明ch ...

  3. UVA1714 Keyboarding

    传送门 坑很多的一题 这里要感谢crk大佬提前帮我把所有的坑都踩了一遍...233 讲一下题目的意思: 给你一个神奇的 r*c 的键盘 (r,c<=50) 上面有大写的字母,数字,' - '号 ...

  4. 搭建element-ui Vue结构

    1.安装淘宝镜像 npm install cnpm -g --registry=https://registry.npm.taobao.org 2.安装webpack cnpm install web ...

  5. Python练习六十:网页分析,找出里面的正文与链接

    网页分析,找出里面的正文与链接 代码如下: from urllib import request from bs4 import BeautifulSoup request = request.url ...

  6. C++二维数组的动态声明

    int **a  =  new int* [m]   //分配一个指针数组,将其首地址保存在a中   . for(int i = 0; i < m; i++)   //为指针数组的每个元素分配一 ...

  7. Vue.js-----轻量高效的MVVM框架(十二、组件动态切换)

    在写html的过程中,我们经常会遇到要写tabs的切换,类似于这样: 在vue中,我们也有自己的组件和属性来实现这样的效果,这个东西我们叫做动态组件. html: <h3>动态组件< ...

  8. Linux下安装&运行Jmeter程序

    Jmeter在linux系统中运行需要安装jdk和Jmeter两个软件: 1.安装JDK 先检查系统是否有安装jdk,在linux中执行如下命令:java -version  如果返回版本信息,说明系 ...

  9. jmeter使用总结

    1.1 什么是 JMeter Apache JMeter 是 Apache 组织开发的基于 Java 的压力测试工具.用于对软件做压力测试,它最初被设计用于 Web 应用测试,但后来扩展到其他测试领域 ...

  10. MapReduce的主要的六个类讲解

    a.InputFormat类.该类的作用是将输入的文件和数据分割成许多小的split文件, 并将split的每个行通过LineRecorderReader解析成<Key,Value>,通过 ...