android:how to check if application is running in background

Update, see this first:

Checking if an Android application is running in the background


To check if your application is sent to background, you can call this code on onPause() on every activity in your application:

 /**
   * Checks if the application is being sent in the background (i.e behind
   * another application's Activity).
   * 
   * @param context the context
   * @return <code>true</code> if another application will be above this one.
   */
  public static boolean isApplicationSentToBackground(final Context context) {
    ActivityManager am = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
    List<RunningTaskInfo> tasks = am.getRunningTasks(1);
    if (!tasks.isEmpty()) {
      ComponentName topActivity = tasks.get(0).topActivity;
      if (!topActivity.getPackageName().equals(context.getPackageName())) {
        return true;
      }
    }

    return false;
  }

For this to work you should include this in your AndroidManifest.xml

<uses-permission android:name="android.permission.GET_TASKS" />

Leave a Comment