Should I use AlarmManager or Handler?

2019-02-03 10:59发布

I'm writing an app that constantly polls the device's sensors and every so often should write down some statistics to a file. This could be as fast as once a second or as slow once a minute. Should I use Handler's postDelayed()method or just schedule it with the AlarmManager?

4条回答
别忘想泡老子
2楼-- · 2019-02-03 11:35

I'd say that it depends on the polling interval. I guess it's quite low in your case (around a few secs), so you should go the Handler way, or by using the Timer class.

AlarmManger is a much higher level service and it involves a larger overhead to handle this use case. When an alarm triggers, you need to handle it with BroadcastReceivers. This means that every time you handle one of these alarm, you needs to register listeners for the sensors you're interested in, which is immensely inefficient imho.

查看更多
Explosion°爆炸
3楼-- · 2019-02-03 11:37

This should help you discriminate between Handler and AlarmManager. [source]

Though it is agreed these mostly work for API 23. It's a new release.

A flowchart for background work, alarms, and your Android app

查看更多
淡お忘
4楼-- · 2019-02-03 11:37

If the app should work in standby then AlarmManager. If not then Handler.
AlarmManager will wake CPU therefore it will drain battery more, while Handler will not work on standby.

查看更多
放我归山
5楼-- · 2019-02-03 11:46

Decide your design based on the below key points:

AlarmManager: The advantage with the AlarmManager is that it works even if the device is in deep sleep mode (CPU is off). When the alarm fires, it hits the BroadcastReceiver and in onReceive, it acquires the wake lock (if you have used WAKEUP types of alarms like RTC_WAKEUP or ELAPSED_TIME_WAKEUP). After finishing the onReceive() it releases the wake lock.

But most of the times it DID NOT WORK for me. So I have acquired my own wake locks in onReceive() and released them at the end to make sure I really get CPU.

The reason why it DID NOT WORK is that when multiple applications simultaneously use a resource (such as wake locks that prevent the system from suspending), the framework spreads CPU consumption across those applications, although not necessarily equally. So, if it is critical, it is always better to acquire wake locks and do the stuff.

Timers and Handlers: Handler and Timers do not work in deep sleep mode meaning the task/runnable will not run as per the schedule when the device is asleep. They do not count the time in sleep which means that the delay given to execute task will be calculated only during active mode. So, actual delay will be delay-given + time-spent-in-deep-sleep.

查看更多
登录 后发表回答