We have an Android app that periodically polls for data and updates the display. The polling is performed by a background thread. Unfortunately, this background thread constantly runs, even when our app is offscreen or when the device is locked, which leads to unnecessary network activity and CPU/battery usage.
So, I would like to change the app such that it will suspend its polling activities in these cases:
- When none of the application’s activities are in the foreground.
- When the device is locked.
What is the easiest way to detect whether the app is in either of these states?
Note: The app has several activities, so I don’t think it is as simple as just keeping track of the activity lifecycle events. I would have to add code to each activity to keep track of whether any of my activities are in the foreground. If that’s what I need to do, I’ll do it, but I’m hoping there is a simpler way.
These are some questions which are related, but which don’t seem to provide a good answer:
For the are-we-in-the-foreground issue, increment a reference count in a static data member in
onStart()of each activity, and decrement it inonStop(). IfonStop()sees0, stop the polling. IfonStart()sees that you’re not polling, start polling.For the is-the-screen-locked issue, don’t worry about it. The device will fall asleep once the screen times out and your polling thread will not be running. Besides, I think your activity will be stopped in this case anyway.
BTW, this is one case where
onStop()is the right answer, notonPause(), so the lifecycle handoff between your activities is handled properly.That’s as simple as it gets.