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: