How to know which Activity is open, running?

Asked

Viewed 571 times

0

I have two activities, Activity1 and Activity2.

I need to know if 2 is active or not in both activities.

Example:

if (activityrunning == activity2){
   //do something
}else{
  //do something else
}

Thank you!

  • but this code will be running in the background as a service?

  • @Neuberoliveira can be in the background, only in a moment inside the app I need to know if it is the 2 that is active.

  • It’s kind of hard to understand what you need, but is it a Fragment that’s in both activityes? And in this Fragment Voce wants to know which Activity is being executed?

  • @Neuberoliveira the answer below solves the problem. Thank you very much!! It is a click that is used in both activities, but if 2, for example is active, it takes to another place in the code! Thanks again!

1 answer

3


One way to do this is to create a static variable and change it according to the life cycle of the Activity. For example, when the method onStart() execute the received variable true. If the onStop(), then the variable will receive the value false. See below:

class MinhaActivity extends Activity {
     static boolean status = false;

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

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

Since the variable is static, you can access its variable from any Activity. Behold:

OutraActivity.status;

Browser other questions tagged

You are not signed in. Login or sign up in order to post.