关于使用 AlarmManager 的注意事项
AlarmManager 和 Jobscheduler
Android后台任务开发的发展和实践(二)
Android 进程保活系列:(三)利用定时器和系统广播
JobService 7.0 定时任务不生效
JobService 总结
场景:周期性的启动Service,执行任务
4.4
AlarmManager manager = (AlarmManager) getSystemService(ALARM_SERVICE);
Intent i = new Intent(this, MessageService.class);
PendingIntent pi = PendingIntent.getService(this, 0, i, 0);
//4.4以上,6.0以下
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
manager.setExact(AlarmManager.ELAPSED_REALTIME_WAKEUP, SystemClock.elapsedRealtime(), pi);
}
//6.0以上
else if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
manager.setExactAndAllowWhileIdle(AlarmManager.ELAPSED_REALTIME_WAKEUP, SystemClock.elapsedRealtime(), pi);
}
//4.4以下
else {
// manager.setRepeating(AlarmManager.ELAPSED_REALTIME_WAKEUP, SystemClock.elapsedRealtime(), triggerAtTime, pi);
manager.set(AlarmManager.ELAPSED_REALTIME_WAKEUP, SystemClock.elapsedRealtime(), pi);
}