Know if Activity is open (Broadcastreceiver or service)

Asked

Viewed 1,273 times

0

I would like to implement a function that can check if Activity is open, because when I receive the notification through GCM (Google Cloud Messaging) if Activity has opened will only upload the information in it, if you have closed notify the user and through this notification he opens the Activity with the information. I want to do this within a service, vlw!

  • At least in the service it didn’t work out. Error > FATAL EXCEPTION: main java.lang.Securityexception: Permission Denial: getTasks() from pid=3792, uid=10096 requires android.permission.GET_TASKS

1 answer

1


You can use a static variable within the Activity, so you can define it by exploring the life cycle onStart() and onStop(). Behold:

class MinhaActivity extends Activity {
     static boolean active = false;

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

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

To access and check if the variable is active or inactive, you can do so:

if(MinhaActivity.active){
    //esta ativa
} else {
    //não está ativa
}
  • but how I will access this variable through the service to get the true or false value?

  • @Rubensventura I edited.

  • worked well here, but when I minimize the app, it’s like finished, in case I should use active = false; in Ondestroy ?

  • @Rubensventura for both onStop and onDestroy you can use active = false. It will work like this.

  • Thank you manow!

Browser other questions tagged

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