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

标签 android

对于这个问题,我经历了很多答案。但这都是关于单个 Activity 的。如何检查整个应用程序是否在前台运行?

最佳答案

我不明白你想要什么,但是你可以使用 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();

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

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

谢谢..

关于android - 检查android应用程序是否在前台?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8489993/

相关文章:

android - 尝试获取位置时避免 Google 提示

android - 如何从自定义 View 开始一项 Activity

android - 从 fragment 开始一个 Activity

sql - 如何正确对 SQL 结果集进行分组?

android - 有一个具有默认高度的 ImageView,当将图像放入其中时更改高度

Android - PendingIntent.getActivity 中的上下文参数

android - 改造 2 : How to set individual timeouts on specific requests?

java - 我可以自定义 Android searchable.xml 布局吗?

java - 带有 JavaScript 界面的 Webview

java - 如何在 Android Studio 中删除导入的模块