AlarmManager 和 ScheduledExecutorService 的区别 [英] Difference between AlarmManager and ScheduledExecutorService

查看:38
本文介绍了AlarmManager 和 ScheduledExecutorService 的区别的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

除了设置和精确时间(即午夜)与设置延迟(即 24 小时)之外,使用 AlarmManagerScheduledExecutorService 定期运行任务有什么区别?

Besides setting and exact time (i.e. midnight) versus setting a delay (i.e. 24 hours), what's the difference between using AlarmManager and ScheduledExecutorService to run a task periodically?

就我而言,我需要每天晚上运行一些代码来检查新数据,并在有新数据时创建新通知.

In my case, I need to run a little bit of code to check for new data every night and create a new notification if there is new data.

谢谢!

推荐答案

ScheduledExecutorService 在您的应用程序进程中运行.如果应用程序进程终止,则不会运行任何计划任务.因此需要 Service(因此您的流程超出了生命周期的活动活动部分).

ScheduledExecutorService runs in your application process. If application process dies, none of the scheduled tasks will run. Hence the need for Service (so your process lives beyond Activities active part of lifecycle).

虽然AlarmManager 是一直运行的关键系统服务.如果您的应用程序安排了某些事情并被终止,那么 AlarmManager 可能会再次启动应用程序(通过 PendingIntent).

While AlarmManager is critical system service that runs all the time. And if your application scheduled something and was killed, then AlarmManager may start application again (via PendingIntent).

这里没有人提到的最后一个主要区别是 AlarmManager 了解 WakeLock 和电源管理.这意味着 AlarmManager 可能会在指定时间唤醒 Android 设备以运行计划任务.而 ScheduledExecutorService 对电源管理一无所知,只会在设备未处于深度睡眠时启动任务(即它可能会错过时间).

And the last major difference that no one mentioned here is that AlarmManager knows about WakeLocks and power management. This means that AlarmManager may wake up Android device at specified time to run scheduled task. While ScheduledExecutorService knows nothing about power management and will only start task when device is not in deep sleep (i.e. it can simply miss the time).

这篇关于AlarmManager 和 ScheduledExecutorService 的区别的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆