android:如何检查应用程序是否在后台运行2

时间:2013-03-18 21:59:32

标签: android android-intent android-activity

我有解决方案。

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;

}

工作正常。

如何检查我的应用程序是否真的在后台?例如,我打开了活动并启动了新的Activity - 标准图库(从我的应用程序启动)。这个意图是从我的活动开始的,我的应用程序在逻辑上处于前台。我可以查看我的活动,但是如何检查这种情况呢?

如何检查应用程序是否已发送到后台FROM外部活动(在此示例 - 库中)?

1 个答案:

答案 0 :(得分: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;
}