虽然Timer、Handler.postDelayed、Thread.sleep方法也可以实现定时任务,但当系统处于休眠状态时,这些定时任务所在进程会被暂停,甚至app被进行垃圾回收,这就意味定时任务将失效。AlarmManager可以帮忙解决这一问题。
AlarmManager(定时管理器)作用:定时唤醒系统(即使休眠状态下)执行任务,相比上述方法,更加节省电池耗电量。
先来一个demo,学习AlarmManager的用法:
1、新建一个DaemonService类:
// 获取系统提供的AlarmManager对象
AlarmManager alarm = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
PendingIntent pendingIntent = PendingIntent.getBroadcast(
this, // context:上下文
0, // requestCode:intent请求标记
new Intent("COM.TEST.NOTIFY_ACTION"), // intent:需要广播出去的intent
PendingIntent.FLAG_UPDATE_CURRENT // flag:intent的控制标签。update_current:新intent覆盖更新旧的未处理的intent;
);
// 设置3分钟重复一次
alarm.setRepeating(AlarmManager.RTC_WAKEUP, System.currentTimeMillis(), 3000, pendingIntent);
2、在MainActivity注册一下BroadcastReceiver
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// 注册一个接收器,专门处理定时任务发过来的intent
alarmReceiver = new AlarmReceiver();
filter = new IntentFilter();
filter.addAction("COM.TEST.NOTIFY_ACTION");
registerReceiver(alarmReceiver, filter);
startService(new Intent(this, DaemonService.class));
}
3、自定义类:AlarmReceiver,处理广播
public class AlarmReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
try {
// 写上定时任务内容 TODO
} catch (Exception e) {}
}
}
step 1 接口参数详解:
- int type
AlarmManager.RTC_WAKEUP:值为0,表示闹钟在睡眠状态下会唤醒系统并执行提示功能,该状态下闹钟使用绝对时间(即当前系统时间)
AlarmManager.RTC:值为1,表示闹钟在睡眠状态下不可用,该状态下闹钟使用绝对时间
AlarmManager.ELAPSED_REALTIME_WAKEUP:值为2,表示闹钟在睡眠状态下会唤醒系统并执行提示功能,该状态下闹钟也使用相对时间(相对于系统启动开始)
AlarmManager.ELAPSED_REALTIME:值为3,表示闹钟在手机睡眠状态下不可用,该状态下闹钟使用相对时间。
AlarmManager.POWER_OFF_WAKEUP:值为4,表示闹钟在手机关机状态下也能正常进行提示功能,用得最多的状态之一,该状态下闹钟也是用绝对时间;不过本状态好像受SDK版本影响,某些版本并不支持 -
ps:1、RTC = Real Time Clock 当前系统的实时时钟
2、RTC闹钟和ELAPSED_REALTIME 最大的差别就是前者可以通过修改手机时间触发闹钟事件,
后者要通过真实时间的流逝,即使在休眠状态,时间也会被计算。
- long triggerAtMillis : 闹钟第一次执行时间,毫秒为单位,需与第一个type参数匹配,
- 如果是RTC类型,triggerAtMillis 则一般使用System.currentTimeMillis();
- 如果是ELAPSED类型,triggerAtMillis 则一般使用SystemClock.elapsedRealtime();
- long intervalMillis : 两次闹钟执行间隔
- PendingIntent operation : 任务的执行动作,发送广播,启动activity,启动service
参考:
https://www.jianshu.com/p/32f438a0c239
https://blog.csdn.net/wei_chong_chong/article/details/51258336