Figuring out if your Application has entered the background is a fairly annoying task in Android. You would think there would be a simple callback like “isInBackground()” that would simply notify the application, but sadly there isn’t.
This means you have to figure out a way on your own to determine the background state. From what I have seen, there's really only one option, and that option involves actually counting live Activities by using the lifecycle methods in each Activity.
To do this efficiently as possible, you need to have a “base” Activity class that all of your real classes inherent from. In this base Activity class, you need to override two methods: onResume and onPause. You would also need a counter variable in the base Activity (or wherever you would like to store it). As you would expect, the onResume method needs to increment the counter, and the onPause method needs to decrement the counter.
Also, the onPause needs to check the counter variable to see if it’s zero. If the counter is zero, then you know your Application is in the background and is not being currently seen by the user. This is because the last Activity started has been paused and no other Activity of your Application has been resumed yet.
New and Improved
The above solution will work on any version of Android. However, on Ice Cream Sandwich (4.0 and API level 14), there is a cleaner solution.
In the Application class, Android now has a new method called unregisterActivityLifecycleCallbacks. This method allows the developer to have one callback that is notified anytime a Activity Lifecycle method is called (onCreate, onResume, etc…). By using this callback, the above counter could be implemented exactly the same, except now, no base Activity class is needed. We simply call this method in the Application class of the Android application and keep track of the currently running Activities there. Now this code doesn’t need to touch every Activity that is created. If only it was back-ported!
Know of any other ways to determine if an Android application has moved into the background?