简体   繁体   English

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

[英]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_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;

} }

It works fine. 工作正常。

How I can to check that my application really in background? 如何检查我的应用程序是否真正在后台? For example, I opened activity and started new Activity - standard Gallery (started from my application). 例如,我打开活动并启动新的活动-标准库(从我的应用程序开始)。 This intent was started from my activity, and my application logically in foreground. 这个意图是从我的活动开始的,而我的应用程序在逻辑上处于前台。 I can check my activities, but how to check this situation too? 我可以检查我的活动,但是如何检查这种情况呢?

AND how can I check that the application was sent to the background FROM external activity (on this example - gallery)? 以及如何检查应用程序是否从外部活动发送到后台(在此示例中-图库)?

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;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM