Removed from this SOen response :
You can take advantage of the activities lifecycle and maintain a flag indicating whether there is a foreground activity. At the end of a transition from one activity to another this flag will have the value true
; if the activity is for background, it will have false
value.
First, create a class responsible for managing the flag that indicates whether any application activity is in the foreground or not.
public class MyApplication extends Application {
public static boolean isActivityVisible() {
return activityVisible;
}
public static void activityResumed() {
activityVisible = true;
}
public static void activityPaused() {
activityVisible = false;
}
private static boolean activityVisible;
}
Note: This class is not required to extend Application
; just use any class with methods globally accessible by the activities. If you choose to extend Application
, be sure to declare the class in AndroidManifest.xml like this:
<application
android:name="pacote.do.aplicativo.MyApplication"
...>
Second, add onPause()
and onResume()
methods to each of the project activities. You can choose to create a parent class that implements these callbacks and make the other activities extend this parent class.
@Override
protected void onResume() {
super.onResume();
MyApplication.activityResumed();
}
@Override
protected void onPause() {
super.onPause();
MyApplication.activityPaused();
}
Now, whenever you want to know if there is a foreground activity, just check by calling MyApplication.isActivityVisible()
. The activities life cycle itself will keep this status updated.
For perfect operation I recommend doing this check always on the main thread. If you check within the onReceive()
method of a broadcast receiver this is already guaranteed, now if you do this within a IntentService
try to use a Handler
.
Restrictions for this approach:
-
You need to include calls in the lifecycle ( onPause
, onResume
) callbacks of all your application's activities, or in an activity-parent that is extended by the others. If you have activities extending ListActivity
or MapActivity
, you will have to add the methods to them individually.
For the check to be accurate you should call the check method from the main thread (if it is called on a secondary thread it may happen to catch a false
value just in the middle of a transition between activities, when the flag transits briefly between the values true
and false
).