Nicholas Nicholas - 2 years ago 388
Android Question

How to check if activity is in foreground or in visible background?

I have a splash screen on a timer. My problem is that before I

my activity I need to check that the next activity has started because a system dialogue box pops-up and I only want to
; once the user has selected an option from the dialogue box?

I know that there are many questions on how to see if your activity is in the foreground but I do not know if this allows for dialogue boxes on top of the activity too.

Here is the problem, the red is my activity which is in the background while the dialogue is in the foreground:

the red is my activity which is in the background while the dialogue is in the foreground

EDIT: I have tried just not using
but then my activity can be gone back to in the stack of applications which I am trying to avoid.

Answer Source

This is what is recommended as the right solution:

The right solution (credits go to Dan, CommonsWare and NeTeInStEiN) Track visibility of your application by yourself using Activity.onPause, Activity.onResume methods. Store "visibility" status in some other class. Good choices are your own implementation of the Application or a Service (there are also a few variations of this solution if you'd like to check activity visibility from the service).

Example Implement custom Application class (note the isActivityVisible() static method):

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;

Register your application class in AndroidManifest.xml:

    android:label="@string/app_name" >

Add onPause and onResume to every Activity in the project (you may create a common ancestor for your Activities if you'd like to, but if your activity is already extended from MapActivity/ListActivity etc. you still need to write the following by hand):

protected void onResume() {

protected void onPause() {

In your finish() method, you want to use isActivityVisible() to check if the activity is visible or not. There you can also check if the user has selected an option or not. Continue when both conditions are met.

The source also mentions two wrong avoid doing that.

Source: stackoverflow

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download