java 定时器和闹钟管理器的区别
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/14579034/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
difference between timer and alarmmanager
提问by mavzey
I am a bit confused about Timer
and AlarmManager
used in Android.
我对Android有点困惑Timer
和AlarmManager
使用。
What are the main differences between them?
它们之间的主要区别是什么?
They are both scheduling a task to run at every A seconds. And what is the main scenario that they are preferred to be used?
他们都安排了一个任务,每 A 秒运行一次。他们更喜欢使用的主要场景是什么?
For example, for X situation, use Timer
but on the other hand, for Y situation, use AlarmManager
.
例如,对于 X 情况,使用Timer
但另一方面,对于 Y 情况,使用AlarmManager
。
回答by Nikolay Elenkov
A Timer
will start a thread that will keep track of when to start your code. If the device goes asleep, so will the timer thread and your code won't be executed on time. AlarmManager
's alarms, on the other hand, are kernel-level. Depending on how you register them, you can request to wake up the device, or execute the next time something wakes up the device. Alarm's are generally preferable and use less resources.
ATimer
将启动一个线程,该线程将跟踪何时启动您的代码。如果设备进入睡眠状态,定时器线程和您的代码也将不会按时执行。AlarmManager
另一方面, 的警报是内核级的。根据您注册它们的方式,您可以请求唤醒设备,或者在下次唤醒设备时执行。警报通常更可取,并且使用较少的资源。
回答by TheWhiteRabbit
Timer starts a service it executes code very frequently even thought it wasn't actually doing anything.
Timer 启动一个服务,它会非常频繁地执行代码,甚至认为它实际上并没有做任何事情。
Alarmmanager on the other hand will start a Service that runs in the background always, this is what you want to use to schedule your code to run when your app isn't open.
另一方面,Alarmmanager 将启动一个始终在后台运行的服务,这是您要用来安排代码在您的应用程序未打开时运行的服务。