0

I have a service that runs periodically using a timer to invoke itself, but should not run when the screen is off. When the screen on event is fired, the service should run, but only if it's past when the timer would have fired.

Right now I still run the timer continually, but have the service do nothing if the screen is off. I can also run the service via a broadcast receiver when the screen turns on - but this runs the service every time the screen is turned on, instead of only when it's past when the timer should have run. Recording this state in the service doesn't seem to work as Android will kill the JVM for the app in between executions.

What would be the cleanest/correct way to implement this type of behavior?

user1234057
  • 353
  • 1
  • 4
  • 10

1 Answers1

0

So there are a couple of intents that you can listen for, Intent.ACTION_SCREEN_OFF and Intent.ACTION_SCREEN_ON. However, these don't work as manifest receivers, they need to be explicitly registered.

See this answer: https://stackoverflow.com/a/9478013/1306452

In all scenarios, it's going to involve a long running service in order to listen for those events.

One thing to keep in mind is that these intents only listen for when the device becomes non-interactive and vice versa, not specifically when the screen goes off (see the description on the Intents).

The best way for you to achieve this behaviour would be to listen for when these intents with a long lived service, started with START_STICKY to help guarantee that the service is running. The service can register a receiver for the SCREEN_ON and OFF events, and when it gets these events either do nothing if the timer has not elapsed, or continue if it has.

This won't be nice on your battery life, and what ever you are doing it doesn't sound like it's going to be a pleasent user experience. You might also want to step back and see if there's another way around this obstacle (my 2 cents).

Community
  • 1
  • 1
Andrew T.
  • 4,598
  • 4
  • 35
  • 54