2

我有解决办法。

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;

}

它工作正常。

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

以及如何检查应用程序是否从外部活动发送到后台(在此示例中 - 画廊)?

4

1 回答 1

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;
}
于 2017-01-02T09:28:20.047 回答