目录
6-1.如何让AlertDialog类只有单击响应按钮时才关闭
8.消息、通知、广播与闹钟(三)
5.使用AlarmManager类设置闹钟
AlarmManager类是Android提供的用于在未来的指定时间弹出一个警告信息,或者完成指定操作的类。实际上AlarmManager是一个全局的定时器,使用它可以在指定的时间或指定的周期启动其他的组件(包括Activity、Service 和BroadcastReceiver)。使用AlarmManager类设置警告后,Android 将自动开启目标应用,即使手机处于休眠状态,因此,使用AlarmManager类也可以实现关机后仍可响应的闹钟。
5-1.AlarmManager 简介
在Android中要获取AlarmManager对象,类似于获取NotificationManager服务,也需要使用Context类的getSystemService()方法来实现,具体代码如下:
Context.getSystemService(Context.ALARM_SERVICE)
获取AlarmManager对象后,就可以应用该对象提供的相关方法来设置警告。AlarmManager 对象提供的常用方法如表8.6所示。
表8.6 AlarmManager 对象的常用方法
方法 | 描述 |
---|---|
cancel(PendingIntent operation) | 取消AlarmManager的定时服务 |
set(int type, long triggerAtTime, PendingIntent operation) | 设置当到达参数triggerAtTime所指定的时间时,按照type参数所指定的服务类型启动由operation 参数指定的组件 |
setlnexactRepeating(int type, long triggerAtTime,long interval, PendingIntent operation) | 设置一个非精确的周期性任务。例如,我们设置一个每个小时启动一次的闹钟,但是系统并不一定总在每个小时开始时启动闹钟 |
setRepeating(int type, long triggerAtTime, long interval, PendingIntent operation) | 设置一个周期性执行的定时服务 |
setTime(long millis) | 设置定时的时间 |
setTimeZone(String timeZone) | 设置系统默认的时区 |
在设置定时服务时,AlarmManager 提供了以下4种类型:
◆ELAPSED_REALTIME
设置从现在时间开始过了一定时间后启动提醒功能。当系统进入睡眠状态时,这种类型的定时不会唤醒系统。直到系统下次被唤醒才传递它,该定时所用的时间是相对时间,是从系统启动后开始计时的(包括睡眠时间),可以通过调用SystemClock.elapsedRealtime()方法获得。
◆ELAPSED_REALTIME_WAKEUP
设置从现在时间开始过了一定时间后启动提醒功能。这种类型的定时能够唤醒系统,即使系统处于休眠状态也会启动提醒功能。使用方法与ELAPSED_REALTIME 类似,也可以通过调用Syst