How Can an Android Application Detect Whether Any of its Activities are Active?
<p>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.</p>

<p>So, I would like to change the app such that it will suspend its polling activities in these cases:</p>

<ul>
<li>When none of the application's activities are in the foreground.</li>
<li>When the device is locked.</li>
</ul>

<p>What is the easiest way to detect whether the app is in either of these states?</p>

<p>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 <em>any</em> 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.</p>

<hr>

<p>These are some questions which are related, but which don't seem to provide a good answer:</p>

<ul>
<li><a href="http://stackoverflow.com/questions/3314838/android-how-to-detect-if-current-stack-of-activities-task-moves-to-background">Android: How to detect if current stack of activities (task) moves to background?</a></li>
<li><a href="http://stackoverflow.com/questions/4668978/how-to-be-notified-about-entering-suspend-mode">How to be notified about entering suspend mode?</a></li>
<li><a href="http://stackoverflow.com/questions/5506959/simple-check-for-android-application-backgrounding">Simple check for Android application backgrounding</a></li>
</ul>
