Drawn of that reply by Soen:
You can take advantage of the activities lifecycle and maintain a flag indicating whether there is an Activity in the foreground. At the end of a transition from one Activity to another this flag will be with the value true; if Activity goes into the background, she’ll be worth false.
First, create a class responsible for managing the flag that indicates if any app Activis 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 does not have to be extended Application; just use any class with globally accessible methods by activities. If you choose to extend Application, do not forget to declare the class in Androidmanifest.xml thus:
<application
android:name="pacote.do.aplicativo.MyApplication"
...>
Second, add methods onPause() and onResume() 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();
}
Ready, now whenever you want to know if there is an Activity in the foreground, just check calling MyApplication.isActivityVisible(). The activities' own life cycle will be in charge of keeping this status up to date.
For perfect working I recommend to always do this check on the main thread. If you are checking inside the method onReceive() of a broadcast receiver that is already guaranteed, now if you do it within a IntentService seek to use a Handler.
Restrictions of that approach:
You need to include calls in lifecycle callbacks (onPause, onResume) of all the activities of your application, or on an Activity-parent that is extended by the others. If you have activities extending ListActivity or MapActivity, will have to add the methods to them individually.
For the check to be accurate you should call the verification method from the main thread (if it is called in a secondary thread it may happen to pick up a value false temporary precisely in the middle of a transition between activities, when the flag transits briefly between values true and false).
It seems right to me the answer, but a doubt, the way you did it will always have to run
new ChecarSegundoPlano().execute(context).get()to get there, correct? I haven’t been working a lot with Java/Android, but if I’m not mistaken have how to extend the classAsyncTaskto theActivityand this would be running on a "Thread automatically", so you wouldn’t have to keep checkingdoInBackgroundperform alone, or I’m mistaken, correct me if I’m wrong. :)– Guilherme Nascimento