Battery Impact: Background Service+BroadcastReceiver VS Polling Every Minute with AlarmManager?

273 views Asked by At

I'm writing an application which needs to detect when the screen turns on or off from the background (with the precision of about 1 minute). Ideally, I'd just statically register for Intent.ACTION_SCREEN_ON and Intent.ACTION_SCREEN_OFF, but unforuntately, that's not allowed.

This leaves me with two not-so-great---actually-pretty-horrible options (unless there's something I'm unaware of, which is likely):

  1. Run a omnipresent Service + BroadcastReceiver which registers for the ACTION_SCREEN_ON and OFF intents OR
  2. Use the AlarmManager to schedule some code to run every minute, and check if the display is on/off with isInteractive()

#1 isn't great because it can be killed, it wastes memory, it needs to be run onboot which doesn't work when installed on the SD card, etc.. the list goes on.

#2 isn't great because it's less precise and... let's face it- polling is almost never the right answer

But worst of all, they will both have a negative impact on battery life. This is actually the most important factor IMHO.

TL;DR

Which is the lesser of the two evils with respect to battery life impact?

1

There are 1 answers

0
Taylor Kidd On

I'm not an android developer (but it would be fun) but when reading the AlarmManager class overview, it says that it will periodically launch an application if it is not running already. This isn't polling as the code isn't running and not affecting performance or keep the processor awake (consuming energy). I'm sure the AlarmManager class itself isn't polling either.

You might also look at suspending your applications process instead and periodically waking it up. Launching a process is typically an expensive operation. Though suspending the application doesn't consume processor resources (and so affect power consumption) it does have a memory footprint.