Android: how do I check if activity is running?

You can use a static variable within the activity.

class MyActivity extends Activity {
     static boolean active = false;

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

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

The only gotcha is that if you use it in two activities that link to each other then onStop on the first is sometimes called after onStart in second. So both might be true briefly.

Depending on what you are trying to do (update the current activity from a service?). You could just register a static listener in the service in your activity onStart method then the correct listener will be available when your service wants to update the UI.


I realize this issue is quite old, but I think it's still worth sharing my solution as it might be useful to others.

This solution wasn't available before Android Architecture Components were released.

Activity is at least partially visible

getLifecycle().getCurrentState().isAtLeast(Lifecycle.State.STARTED)

Activity is in the foreground

getLifecycle().getCurrentState().isAtLeast(Lifecycle.State.RESUMED)