程序员

【Android 基础】AlarmManager 使用

2017-07-24  本文已影响84人  dongbingliu
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 主要方法:

关键参数讲解

AlarmManager.ELAPSED_REALTIME 系统相对时间(BootComplete开始计算),闹钟睡眠状态不可用;
AlarmManager.ELAPSED_REALTIME_WAKEUP 相对时间,休眠时间可用
AlarmManager.RTC 绝对时间
AlarmManager.RTC_WAKEUP 绝对时间,休眠可用
AlarmManager.POWER_OFF_WAKEUP 绝对时间,关机休眠可用

定义PendingIntent 对象

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

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

//发送BroadCastIntent广播
PendingIntent pendingIntentBroadCast = PendingIntent.getBroadcast();
上一篇 下一篇

猜你喜欢

热点阅读