Question

In my app, there are several cases in which I should know which activity is visible to the user.

  • Is there a function to get the current activity visible to the user ?

Right now what I am doing is create a class with static variables such as

boolean static mainActivityIsVisible = false;

Which get toggled between true/false inside onResume() and onPause(); hence, other activities can check this variable to find out.

Does the same apply to check if an activity is stopped or destroyed ? Or is there a way to check the activities from the stack of the app ?

finally

How can I find that the last activity's onDestroy() was called. My objective from this is to find out if the app has totally exited and does not have any activities running, nor is minimized. 

The question can be rephrased by

How can I know my activity is not running."

and

How can I know my activity is running but not visible to the user ?
Was it helpful?

Solution

You can use this :

1) How can i know if activity is running or not?

class MyActivity extends Activity {
     static boolean active = false;

      @Override
      public void onStart() {
         super.onStart();
         active = true;
      } 

      @Override
      public void onStop() {
         super.onStop();
         active = false;
      }
}

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

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:

<application
    android:name="your.app.package.MyApplication"
    android:icon="@drawable/icon"
    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):

@Override
protected void onResume() {
  super.onResume();
  MyApplication.activityResumed();
}

@Override
protected void onPause() {
  super.onPause();
  MyApplication.activityPaused();
}

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.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top