首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >android学习笔记--AlarmManager

android学习笔记--AlarmManager

作者头像
yuanyuan
发布2019-09-10 17:59:35
5990
发布2019-09-10 17:59:35
举报
文章被收录于专栏:小满小满

AlarmManager称呼为全局定时器,有的称呼为闹钟。其实它的作用和Timer有点相似。

都有两种相似的用法:

(1)在指定时长后执行某项操作(2)周期性的执行某项操作

AlarmManager 包含的主要方法:

// 取消已经注册的与参数匹配的定时器 void cancel(PendingIntent operation) //注册一个新的延迟定时器 void set(int type, long triggerAtTime, PendingIntent operation) //注册一个重复类型的定时器 void setRepeating(int type, long triggerAtTime, long interval, PendingIntent operation) //注册一个非精密的重复类型定时器 void setInexactRepeating (int type, long triggerAtTime, long interval, PendingIntent operation) //设置时区 void setTimeZone(String timeZone)

AlarmManager对象配合Intent使用,可以定时的开启一个Activity,发送一个BroadCast,或者开启一个Service.

android提供了的几种类型的闹钟:

public static final int ELAPSED_REALTIME 在指定的延时过后,发送广播,但不唤醒设备。// 当系统进入睡眠状态时,这种类型的闹铃不会唤醒系统。直到系统下次被唤醒才传递它,该闹铃所用的时间是相对时间,是从系统启动后开始计时的,包括睡眠时 间,可以通过调用SystemClock.elapsedRealtime()获得。系统值是3 (0x00000003)。 public static final int ELAPSED_REALTIME_WAKEUP 在指定的延时后,发送广播,并唤醒设备 //能唤醒系统,用法同ELAPSED_REALTIME,系统值是2 (0x00000002) 。 public static final int RTC 在指定的时刻,发送广播,但不唤醒设备 //当系统进入睡眠状态时,这种类型的闹铃不会唤醒系统。直到系统下次被唤醒才传递它,该闹铃所用的时间是绝对时间,所用时间是UTC时间,可以通过调用 System.currentTimeMillis()获得。系统值是1 (0x00000001) 。 public static final int RTC_WAKEUP 在指定的时刻,发送广播,并唤醒设备//能唤醒系统,用法同RTC类型,系统值为 0 (0x00000000) 。 Public static final int POWER_OFF_WAKEUP //能唤醒系统,它是一种关机闹铃,就是说设备在关机状态下也可以唤醒系统,所以我们把它称之为关机闹铃。使用方法同RTC类型,系统值为4(0x00000004)。

见api/app/alarm/AlarmController实例

demo:

AlarmManager mgr = (AlarmManager) context .getSystemService(Context.ALARM_SERVICE);

Intent i = new Intent(context, MyAlarmService.class); i.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);

PendingIntent pi = PendingIntent.getService(context, 0, i, 0);

//设置触发时间

GregorianCalendar now = new GregorianCalendar(); GregorianCalendar targetTime = new GregorianCalendar();

targetTime.set(GregorianCalendar.HOUR_OF_DAY, 2); targetTime.set(GregorianCalendar.MINUTE, 0);

long diff = targetTime.getTimeInMillis() - now.getTimeInMillis();

if (diff < 0) // passerat 2am diff += AlarmManager.INTERVAL_DAY;

//注册一个重复类型的定时器 mgr.setRepeating(AlarmManager.ELAPSED_REALTIME_WAKEUP, SystemClock.elapsedRealtime() + diff, AlarmManager.INTERVAL_DAY, pi);

本文参与 腾讯云自媒体分享计划,分享自作者个人站点/博客。
原始发表:2014-06-24 ,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档