Search code examples
androidalarmmanagerandroid-sensorsandroid-wake-lock

android sensor event slows down when device screen is off for a while


I'm trying to collect accelerometer values at 50ms period and do something with collected values at every 1 minute. So i used alarm manager with 1 minute pending intent with RTC_WAKEUP flag and set sensor event to 50ms. It first seemed that sensor event was called well with exact time period and collected 1150~1210 accelerometer values at every one minute passed even when my device screen is off, but when i unplugged my device from computer and turn screen power off, it started to become slower, at the end it collected only 60~100 samples at every 1 minute. So i currently acquire Wakelock whole time and replaced alarm manager with timer to do timer taske at every 1 minute. But i'm worried of drain of my battery.

So what i wanna ask you are below"

1) Is device awake when device is plugged to computer or recharger?

2) What method would be better for battery life? Using alarm maganer to acquire wakelock every 2 second to stay device awake and do something when it reaches 1 minute? Or using current method of acquiring Wakelock for whole time to make device alive and use timer to do something every 1 minute?


Solution

  • I found that phone is alive only when it is plugged to computer. After unplugged from computer, phone slowed collecting sensor values few minutes later. So i changed my AlarmManager to fire alarm intent every 2 second to do both timing task and keeping device awake. But phone sometimes didn't fire alarm intent every 2 second at exact time, which was critical to purpose of my application. So i changed method to keep phone alive from using AlarmManager to just hold Wakelock whole time and used Timer and Timertask to do timing task. After timer did all timing task then it release wakelock. Code inside sensor event only collect sample and put sample into queue and in timer task at every 2 second, it transformed collected samples to frequency domain using fft, which needs a lot of calcultion.

    I read many posts that holding wakelock is really inefficient when it comes to battery life. But when i hold wakelock, i checked cpu usage during each timer task and sensor event being processed, each 2 second and 50ms period. It used only like 0.71~1.75 % of total cpu usage every second!! Which i thought not that bad for battery life. So then i tested again by holding wakelock for 7 hours with same period for timer task and sensor event. The result was that it used less than 10% of battery, and collected sensor values samples almost exact every 50ms and also timer task at almost exact every 2 second!!

    I antipated more battery usage because of weight of the code in each timer task and sensor event. I'm happy to know that if i carefully design timing task code, it is not that bad for battery life even though holding wakelock and keeping cpu of phone alive!!