美文网首页程序员
【Android 基础】AlarmManager 使用

【Android 基础】AlarmManager 使用

作者: dongbingliu | 来源:发表于2017-07-24 21:48 被阅读84次
image.png

项目中使用到定时任务,使用Timer 与 TimerTask 类完成定时,但 app 退出后,Timer 定时器会失效,app 为系统签名,在其AndroidManifest.xml 添加persist属性,后期项目内存吃紧,需要优化内存,去掉app persist属性(只有系统签名才可以使用persist签名,杀不死),在同事的建议下,使用AlarmManager 替换Timer定时器任务,AlarmManager 在 app finish 后,继续定时器任务,等时间到后会发送广播;

获取AlarmManager实例对象

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

AlarmManager 主要方法:

  • set(int type,long startTime,PendingIntent pi):一次性闹钟
  • setRepeating(int type,long startTime,long intervalTime,PendingIntent pi)
    重复性闹钟
  • setInexactRepeating(int type,long startTime,long intervalTime,PendingIntent pi) 重复性闹钟,时间不固定
  • cancel(PendingIntent pi) 取消AlarmManager的定时服务

关键参数讲解

  • Type(闹钟类型)
AlarmManager.ELAPSED_REALTIME 系统相对时间(BootComplete开始计算),闹钟睡眠状态不可用;
AlarmManager.ELAPSED_REALTIME_WAKEUP 相对时间,休眠时间可用
AlarmManager.RTC 绝对时间
AlarmManager.RTC_WAKEUP 绝对时间,休眠可用
AlarmManager.POWER_OFF_WAKEUP 绝对时间,关机休眠可用
  • startTime 闹钟第一次执行时间,毫秒为单位,需与第一个Type参数匹配
  • intervalTime 两次闹钟执行间隔
  • PendingIntent 绑定了闹钟的执行动作,发送广播启动activity启动service

定义PendingIntent 对象

//启动ActivityIntent
PendingIntent pendingIntentAcitivy = PendingIntent.getActivities();

//启动ServiceIntent
PendingIntent pendingIntentService = PendingIntent.getService();

//发送BroadCastIntent广播
PendingIntent pendingIntentBroadCast = PendingIntent.getBroadcast();

相关文章

网友评论

    本文标题:【Android 基础】AlarmManager 使用

    本文链接:https://www.haomeiwen.com/subject/kjfikxtx.html