Android Alarm manager 定时闹钟开发详解

来源:互联网 发布:notepad怎么运行python 编辑:程序博客网 时间:2024/04/27 21:37
下文出自:http://www.cxy.me/doc/5888.htm

Alarm manager 主要管理硬件时钟。

一些与时间相关的应用,如日历,闹钟等需要使用Alarm Manager的服务。Alarm manager功能相对比较简单,相关代码位于
frameworks/base/core/jni/server/com_android_server_AlarmManagerService.cpp
frameworks/base/services/java/com/android/server/AlarmManagerService.java

一. frameworks/base/core/jni/server/com_android_server_AlarmManagerService.cpp
这部分代码直接管理硬件时钟,设备名为/dev/alarm。包括打开设备,关闭设备,设置时区,设置触发时间(timeout),以及等待时钟触发。
二. frameworks/base/services/java/com/android/server/AlarmManagerService.java
这部分封装目录一中的代码,向上提供java接口,同时与客户端(如calendar)交互,接收来自客户端的时钟设置请求,并在时钟触发时通知客户端。

Alarm是在预定的时间上触发Intent的一种独立的方法。

 

Alarm超出了应用程序的作用域,所以它们可以用于触发应用程序事件或动作,甚至在应用程序关闭之后。与Broadcast Receiver结合,它们可以变得尤其的强大,可以通过设置Alarm来启动应用程序或者执行动作,而应用程序不需要打开或者处于活跃状态。

 

举个例子,你可以使用Alarm来实现一个闹钟程序,执行正常的网络查询,或者在“非高峰”时间安排耗时或有代价的操作。

 

对于仅在应用程序生命周期内发生的定时操作,Handler类与Timer和Thread类的结合是一个更好的选择,它允许Android更好地控制系统资源。

 

Android中的Alarm在设备处于睡眠模式时仍保持活跃,它可以设置来唤醒设备;然而,所有的Alarm在设备重启时都会被取消。

 

Alarm的操作通过AlarmManager来处理,通过getSystemService可以获得其系统服务,如下所示:

 

AlarmManager alarms = (AlarmManager)getSystemService(Context.ALARM_SERVICE);

 

为了创建一个新的Alarm,使用set方法并指定一个Alarm类型、触发时间和在Alarm触发时要调用的Intent。如果你设定的Alarm发生在过去,那么,它将立即触发。

 

这里有4种Alarm类型。你的选择将决定你在set方法中传递的时间值代表什么,是特定的时间或者是时间流逝:

 

❑ RTC_WAKEUP

在指定的时刻(设置Alarm的时候),唤醒设备来触发Intent。

 

❑ RTC

在一个显式的时间触发Intent,但不唤醒设备。

 

❑ ELAPSED_REALTIME

从设备启动后,如果流逝的时间达到总时间,那么触发Intent,但不唤醒设备。流逝的时间包括设备睡眠的任何时间。注意一点的是,时间流逝的计算点是自从它最后一次启动算起。

 

❑ ELAPSED_REALTIME_WAKEUP

从设备启动后,达到流逝的总时间后,如果需要将唤醒设备并触发Intent。

 

Alarm的创建过程演示如下片段所示:

 

int alarmType = AlarmManager.ELAPSED_REALTIME_WAKEUP;

long timeOrLengthofWait = 10000;

String ALARM_ACTION = “ALARM_ACTION”;

Intent intentToFire = new Intent(ALARM_ACTION);

PendingIntent pendingIntent = PendingIntent.getBroadcast(this, 0, intentToFire, 0);

alarms.set(alarmType, timeOrLengthofWait, pendingIntent);

 

当Alarm到达时,你指定的PendingIntent将被触发。设置另外一个Alarm并使用相同的PendingIntent来替代之前存在的Alarm。

 

取消一个Alarm,调用AlarmManager的cancel方法,传入你不再希望被触发的PendingIntent,如下面的代码所示:

 

alarms.cancel(pendingIntent);

 

接下来的代码片段中,设置了两个Alarm,随后马上取消了第一个Alarm。第一个Alarm显式地设置了在特定的时间唤醒设备并发送Intent。第二个设置为从设备启动后,流逝时间为30分钟,到达时间后如果设备在睡眠状态也不会唤醒它。

 

AlarmManager alarms = (AlarmManager)getSystemService(Context.ALARM_SERVICE);

 

String MY_RTC_ALARM = “MY_RTC_ALARM”;

String ALARM_ACTION = “MY_ELAPSED_ALARM”;

PendingIntent rtcIntent = PendingIntent.getBroadcast(this, 0, new Intent(MY_RTC_ALARM), 1);

PendingIntent elapsedIntent = PendingIntent.getBroadcast(this, 0, new Intent(ALARM_ACTION), 1);

 

// Wakeup and fire intent in 5 hours.(注释可能有错)

Date t = new Date();

t.setTime(java.lang.System.currentTimeMillis() + 60*1000*5);

alarms.set(AlarmManager.RTC_WAKEUP, t.getTime(), rtcIntent);

 

// Fire intent in 30 mins if already awake.

alarms.set(AlarmManager.ELAPSED_REALTIME, 30*60*1000, elapsedIntent);

 

// Cancel the first alarm.

alarms.cancel(rtcIntent);


下文出自:http://www.cnblogs.com/melaniedeng/archive/2012/02/16/2355066.html

关于android自动关机,网上有很多应用程序和例子。 相对于自动开机来说,自动关机可以在应用层通过设置alarm来实现。而自动开机,网上的介绍就比较少了,因为它需要底层rtc时钟的支持。前段时间根据客户需求实现了自动开关机。在这里分享一下。

1. 简介

我的实现是在设置程序里面增加一个接口,让用户设置自动开关机,这个自动开关机的设置可以参照闹钟的设置。关于自动关机,考虑到关机的时候,用户可能正有一些重要的操作,那么应该给用户一个机会去取消当前的关机。

1)一个BroadcastReceiver, 接收如下信息:

  a) 自定义的ACTION_REQUEST_POWER_OFF:设置auto power off时,通过AlarmManager设置的一个RTC_WAKEUP时钟。当到设置的关机时间时,之前设置到AlarmManager的这个action会被广播。我们实现的这个BroadcastReceiver接收到这个消息后,就要开始power off流程

  b) 自定义的ACTION_REQUEST_POWER_ON:设置auto power on时,通过AlarmManager设置的一个RTC_WAKEUP时钟。我们知道power on的应该设置一个rtc的alarm,那么这个RTC_WAKEUP的alarm是做什么的呢?其实当用户设置自动关机的时候,我设置了2个时钟,一个是RTC时钟,用于关机状态下开机;还有一个就是这个RTC_WAKEUP时钟。之所以设置这个时钟,其实是这样的,比如说你设置了周一到周五每天7点半自动开机,而周四早上你7点就打开了手机,这样到7点半的时候,之前设置的时钟就过期了,如果不重新设置的话,周五早上是不会自动开机的。所以这个时候,之前设置的RTC_WAKEUP就接收到了这样的信息,在重新设置下次自动开机的时钟。

  c) BOOT_COMPLETE和TIMEZONE changed, Time set等时间相关的action:当系统开机完成或时间、时区发生改变时,都需要重新设置alarm。

2)一个处理power off 的Service,当BroadcastReceiver接收到ACTION_REQUEST_POWER_OFF,我们给用户一个机会去取消当前的自动关机。这个Service的作用就是启动一个无背景的页面,给用户提示。同时播放之前用户设置的提示音或振动。

3)一个Activity:显示一个dialog提示用户要自动关机,并用一个计时器倒计时。当用户确认关机,或者计时器到时间的时候,就关机。否则取消当前关机,并重设下次自动关机alarm。


2. 自动关机的实现。自动关机的实现比较简单,这里主要说一下怎么设置alarm,和实现关机:

1) 设置自动关机的alarm:

 

复制代码
    AlarmManager am = (AlarmManager) context                .getSystemService(Context.ALARM_SERVICE);        Intent intent = new Intent(                "com.android.settings.action.REQUEST_POWER_OFF");        PendingIntent pendingIntent = PendingIntent.getBroadcast(context, 0,                intent, PendingIntent.FLAG_CANCEL_CURRENT);        am = (AlarmManager) context                .getSystemService(Context.ALARM_SERVICE);        am.set(AlarmManager.RTC_WAKEUP, time, pendingIntent);
复制代码

2)自动关机掉的是./frameworks/base/services/java/com/android/server/ShutdownActivity.java:

        Intent newIntent = new Intent(Intent.ACTION_REQUEST_SHUTDOWN);        newIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);        startActivity(newIntent);

Intent.ACTION_REQUEST_SHUTDOWN是Intent里面一个隐藏的action。

 

3. 自动开机的实现。一直在做上层应用和framework,对于底层不是很熟悉。正好有同事之前做过关机闹铃,所以把他之前的实现稍加改动就可以了。在系统power off的状态下自动开机,我们需要设置一个rtc时钟,当用户设置自动开机时,由AlarmManagerService将时钟设置下去。这学要底层的支持。这里的实现是定义一个我们自己的rtc alarm type:

1) 首先要在头文件里面定义:

  a) kernel/include/linux/android_alarm.h

复制代码
#define ANDROID_ALARM_GET_TIME(type)        ALARM_IOW(4, type, struct timespec)#define ANDROID_ALARM_SET_RTC               _IOW('a', 5, struct timespec)/* we define ANDROID_RTC_ALARM_SET for auto power off */#define ANDROID_RTC_ALARM_SET               _IOW('a', 7, int)#define ANDROID_ALARM_BASE_CMD(cmd)         (cmd & ~(_IOC(0, 0, 0xf0, 0)))
复制代码

  b) bionic/libc/kernel/common/linux/android_alarm.h

#define ANDROID_RTC_ALARM_SET _IOW('a', 7, int)

2) 定义完成之后,还需要实现:在kernel/drivers/rtc/alarm-dev.c文件的alarm_ioctl方法里面,增加一个case,实现设置alarm

复制代码
    case ANDROID_RTC_ALARM_SET:        {            unsigned int rtc_alarm_time;            struct rtc_time rtc_now;            if (copy_from_user(&rtc_alarm_time, (void __user *)arg,                sizeof(rtc_alarm_time))) {                rv = -EFAULT;                goto err1;            }            if (pmic_rtc_get_time(&rtc_now) < 0) {                rtc_now.sec = 0;                if (pmic_rtc_start(&rtc_now) < 0) {                    printk("get and set rtc info failed\n");                    break;                }            }            pmic_rtc_disable_alarm(PM_RTC_ALARM_1);            rtc_now.sec += rtc_alarm_time;            pmic_rtc_enable_alarm(PM_RTC_ALARM_1, &rtc_now);            break;        }
复制代码

当然不要忘记增加一个include:

#include <mach/pmic.h>

3)在frameworks/base/services/jni/com_android_server_AlarmManagerService.cpp里面增加一个方法去设置时钟:

复制代码
static void android_server_AlarmManagerService_updateRtcAlarm(JNIEnv* env, jobject obj, jint fd, jint seconds){#if HAVE_ANDROID_OS    int result = ioctl(fd, ANDROID_RTC_ALARM_SET, &seconds);    LOGE("set rtc alarm to %d later: %s\n", seconds, strerror(errno));    if (result < 0)    {        LOGE("Unable to set rtc alarm to %d later: %s\n", seconds, strerror(errno));    }#endif}
复制代码

还有就是不要忘记定义一下接口:

{"updateRtcAlarm", "(II)V", (void*)android_server_AlarmManagerService_updateRtcAlarm},

4) 在frameworks/base/services/java/com/android/server/AlarmManagerService.java里面定义native的设置alarm的方法,然后调用就可以实现将自动关机的alarm设置下去了:

定义:private native void updateRtcAlarm(int fd, int seconds);

调用:

复制代码
    public void setRepeating(int type, long triggerAtTime, long interval,             PendingIntent operation) {        if (operation == null) {            Slog.w(TAG, "set/setRepeating ignored because there is no intent");            return;        }        synchronized (mLock) {            Alarm alarm = new Alarm();            alarm.type = type;            alarm.when = triggerAtTime;            alarm.repeatInterval = interval;            alarm.operation = operation;            // Remove this alarm if already scheduled.            removeLocked(operation);            if (localLOGV) Slog.v(TAG, "set: " + alarm);            int index = addAlarmLocked(alarm);            if (index == 0) {                setLocked(alarm);            }            // Start to setup auto power on alarm            if ((alarm.type == AlarmManager.ELAPSED_REALTIME_WAKEUP) &&                                 alarm.operation.getTargetPackage().equals("com.android.settings")) {                updateRtcAlarm(mDescriptor, (int)((alarm.when - System.currentTimeMillis()) / 1000));            }            // End to setup auto power on alarm        }    }
复制代码

5)在应用层设置自动开机

复制代码
        AlarmManager am = (AlarmManager) context                .getSystemService(Context.ALARM_SERVICE);        Intent intent = new Intent(                "com.android.settings.action.REQUEST_POWER_ON");        PendingIntent pendingIntent = PendingIntent.getBroadcast(context, 0,                intent, PendingIntent.FLAG_CANCEL_CURRENT);        am = (AlarmManager) context                .getSystemService(Context.ALARM_SERVICE);        am.set(AlarmManager.ELAPSED_REALTIME_WAKEUP, time, pendingIntent);
复制代码


4. 总结

1) 自动开机原理比较简单,但是需要底层的支持,所以对于做应用或者framework层的技术人员来说,实现起来稍微比较麻烦。
2) 在设置自动开关机的时候,需要考虑的情况很多,比如是否设置时间/时区的改变,手机当前是开机还是关机状态等。



闹钟代码示例:http://blog.csdn.net/wang_yubin/article/details/8440837


原创粉丝点击