user560571 user560571 - 1 year ago 483
Android Question

Android: how do I check if activity is running?

Is there any simple way of determining whether or not a certain activity is active?
I want to do certain things depending on which activity is active.

if(activityrunning= activity1)
//do this
else if (activityrunning= activity2)
//do something else

Answer Source

You can use a static variable within the activity.

class MyActivity extends Activity {
     static boolean active = false;

      public void onStart() {
         active = true;

      public void 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.

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