Skip to content Skip to sidebar Skip to footer

Android:how To Check If Application Is Running In Background 2

I have the solution. public static boolean isApplicationSentToBackground(final Context context) { ActivityManager am = (ActivityManager) context.getSystemService(Context.ACTIVITY_S

Solution 1:

public boolean isApplicationSentToBackground(final Context context) {

  Boolean flag = false;
  ActivityManager am = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
  if (Build.VERSION.SDK_INT >= 23) {
    List < ActivityManager.RunningTaskInfo > tasks = am.getRunningTasks(1);
    if (!tasks.isEmpty()) {
      ComponentName topActivity = tasks.get(0).topActivity;
      if (!topActivity.getPackageName().equals(context.getPackageName())) {
        flag = true;
      }
    }
  } else {
    try {
      Thread.sleep(1500);
      flag = false;
      List < ActivityManager.RunningAppProcessInfo > runningProcesses = am.getRunningAppProcesses();
      for (ActivityManager.RunningAppProcessInfo processInfo: runningProcesses) {
        if (processInfo.importance == ActivityManager.RunningAppProcessInfo.IMPORTANCE_BACKGROUND) {
          for (String activeProcess: processInfo.pkgList) {
            if (activeProcess.equals(context.getPackageName())) {
              flag = true;
            }
          }
        }
      }
    } catch (Exception e) {
      e.printStackTrace();
    }
  }
  return flag;
}

Post a Comment for "Android:how To Check If Application Is Running In Background 2"