检查android应用程序是否在前台?

参见英文答案 > Checking if an Android application is running in the background                                    29个
>            Check whether activity is active                                    6个
>            Determining the current foreground application from a background task or service                                    13个
我为这个问题经历了很多答案.但这都是关于单一活动的.如何检查整个应用程序是否在前台运行?
最佳答案
我不明白你想要什么,但你可以使用ActivityManager.getRunningAppProcesses()调用检测当前的前台/后台应用程序.

就像是,

class ForegroundCheckTask extends AsyncTask<Context, Void, Boolean> {

  @Override
  protected Boolean doInBackground(Context... params) {
    final Context context = params[0].getApplicationContext();
    return isAppOnForeground(context);
  }

  private boolean isAppOnForeground(Context context) {
    ActivityManager activityManager = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
    List<RunningAppProcessInfo> appProcesses = activityManager.getRunningAppProcesses();
    if (appProcesses == null) {
      return false;
    }
    final String packageName = context.getPackageName();
    for (RunningAppProcessInfo appProcess : appProcesses) {
      if (appProcess.importance == RunningAppProcessInfo.IMPORTANCE_FOREGROUND && appProcess.processName.equals(packageName)) {
        return true;
      }
    }
    return false;
  }
}

// Use like this:
boolean foregroud = new ForegroundCheckTask().execute(context).get();

如果我误解了,也请告诉我.

更新:请看这个问题Determining the current foreground application from a background task or service更多信息..

谢谢..

转载注明原文:检查android应用程序是否在前台? - 代码日志