Run code when Android app is closed/sent to background

Check this solution first https://stackoverflow.com/a/5862048/1037294 before you decide to use the code below!


To check if your application is sent to background, you can call this code on onPause() or onStop() 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