How to know if the app is open

Asked

Viewed 3,216 times

3

I wonder if there is how to check if the application is open, with user using it or if it is in the background and he is using another application.

Depending if you have it open and user using it I will make a function, if it has not I will execute another command.

4 answers

1

Try to use this code.

private boolean verifyApplicationRunning(Context context) {
        ActivityManager activityManager = (ActivityManager) context.getSystemService(context.ACTIVITY_SERVICE);
        List<RunningAppProcessInfo> procInfos = activityManager.getRunningAppProcesses();
        for (int i = 0; i < procInfos.size(); i++) {
            if (procInfos.get(i).processName.equals(NOME_DO_PACOTE)) {
                onDestroy();
                return true;
            }
        }
        return false;
    }

1

Drawn of that reply by Soen:

You can take advantage of the activities lifecycle and maintain a flag indicating whether there is an Activity in the foreground. At the end of a transition from one Activity to another this flag will be with the value true; if Activity goes into the background, she’ll be worth false.

First, create a class responsible for managing the flag that indicates if any app Activis is in the foreground or not.

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;
}

Note: This class does not have to be extended Application; just use any class with globally accessible methods by activities. If you choose to extend Application, do not forget to declare the class in Androidmanifest.xml thus:

<application
    android:name="pacote.do.aplicativo.MyApplication"
    ...>

Second, add methods onPause() and onResume() to each of the project activities. You can choose to create a parent class that implements these callbacks and make the other activities extend this parent class.

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

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

Ready, now whenever you want to know if there is an Activity in the foreground, just check calling MyApplication.isActivityVisible(). The activities' own life cycle will be in charge of keeping this status up to date.

For perfect working I recommend to always do this check on the main thread. If you are checking inside the method onReceive() of a broadcast receiver that is already guaranteed, now if you do it within a IntentService seek to use a Handler.

Restrictions of that approach:

  • You need to include calls in lifecycle callbacks (onPause, onResume) of all the activities of your application, or on an Activity-parent that is extended by the others. If you have activities extending ListActivity or MapActivity, will have to add the methods to them individually.

  • For the check to be accurate you should call the verification method from the main thread (if it is called in a secondary thread it may happen to pick up a value false temporary precisely in the middle of a transition between activities, when the flag transits briefly between values true and false).

0

You can use a class to check if the app is in the background with ActivityManager.getRunningAppProcesses().

class ChecarSegundoPlano extends AsyncTask<Context, Void, Boolean> {

  @Override
  protected Boolean doInBackground(Context... params) {
    final Context context = params[0].getApplicationContext();
    return isAppOnForeground(context);
  }

  private boolean isAppOnForeground(Context context) {
    ActivityManager activityManager = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
    List<RunningAppProcessInfo> appProcesses = activityManager.getRunningAppProcesses();
    if (appProcesses == null) {
      return false;
    }
    final String packageName = context.getPackageName();
    for (RunningAppProcessInfo appProcess : appProcesses) {
      if (appProcess.importance == RunningAppProcessInfo.IMPORTANCE_FOREGROUND && appProcess.processName.equals(packageName)) {
        return true;
      }
    }
    return false;
  }
}

// Execute com isto. Quando foregroud for true, sua aplicação estará em primeiro plano.
boolean foregroud = new ChecarSegundoPlano().execute(context).get();

Law more...

  • It seems right to me the answer, but a doubt, the way you did it will always have to run new ChecarSegundoPlano().execute(context).get() to get there, correct? I haven’t been working a lot with Java/Android, but if I’m not mistaken have how to extend the class AsyncTask to the Activity and this would be running on a "Thread automatically", so you wouldn’t have to keep checking doInBackground perform alone, or I’m mistaken, correct me if I’m wrong. :)

0

To implement what you want, we need to understand a little bit about the life cycle of a Activity.

  • onCreate() is where you boot your Activity. Here you call the method setContentView() with your . xml file and through findViewById() you reference your widgets.

  • onStart() is called when its Activity is visible to the user. This method can be called several times, including after the onCreate())

  • onResume() is called when its Activity will start the interface with the user.

  • onPause(), unlike the onResume() is called when the system is about to start another Activity already created. Here it is usually used to save/persist data, stop animations etc.

  • onStop(), unlike the method onStart() is called when your Activity is no longer visible to the user as another Activity is being summarized and is covering your.

Now, just you understand and analyze what best fits your need to fire your method.

References:

http://developer.android.com/training/basics/activity-lifecycle/starting.html http://developer.android.com/reference/android/app/Activity.html

Browser other questions tagged

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