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
?
相关问题
- How can I create this custom Bottom Navigation on
- Bottom Navigation View gets Shrink Down
- How to make that the snackbar action button be sho
- Listening to outgoing sms not working android
- How to create Circular view on android wear?
相关文章
- android开发 怎么把图片放入drawable的文件夹下
- android上如何获取/storage/emulated/下的文件列表
- androidStudio有个箭头不认识
- SQLite不能创建表
- Windows - Android SDK manager not listing any plat
- Animate Recycler View grid when number of columns
- Why is the app closing suddenly without showing an
- Android OverlayItem.setMarker(): Change the marker
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.
This should help you discriminate between
Handler
andAlarmManager
. [source]Though it is agreed these mostly work for API 23. It's a new release.
If the app should work in standby then
AlarmManager
. If not thenHandler
.AlarmManager
will wake CPU therefore it will drain battery more, whileHandler
will not work on standby.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 theBroadcastReceiver
and inonReceive
, it acquires the wake lock (if you have usedWAKEUP
types of alarms likeRTC_WAKEUP
orELAPSED_TIME_WAKEUP
). After finishing theonReceive()
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.