如何检查该应用程序是否正在运行(Android> 5.1)?

时间:2017-10-10 09:39:50

标签: android

下面的代码在Android 4.4上成功运行,但是因为android 5.1 getRunningAppProcesses()只返回自己的进程。如何检查应用程序是否在Android上运行> 5.1

static boolean isRun(Context context, String pkg_name) {
    ActivityManager activityManager = (ActivityManager) context.getSystemService(context.ACTIVITY_SERVICE);
    List<ActivityManager.RunningAppProcessInfo> procInfos = activityManager.getRunningAppProcesses();
    if (procInfos == null)
        return false;
    int i;
    for (i = 0; i < procInfos.size(); i++) {
        ActivityManager.RunningAppProcessInfo proc = procInfos.get(i);
        if (proc.processName.equals(pkg_name))
            return true;
    }
    return false;
}

对于Android 5.1及更高版本,使用什么代替getRunningAppProcesses()。

1 个答案:

答案 0 :(得分:1)

/ **      *方法检查应用程序是否在后台      * /

  public static boolean isAppIsInBackground(Context context) {
        boolean isInBackground = true;
        ActivityManager am = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
        if (Build.VERSION.SDK_INT > Build.VERSION_CODES.KITKAT_WATCH) {
            List<ActivityManager.RunningAppProcessInfo> runningProcesses = am.getRunningAppProcesses();
            for (ActivityManager.RunningAppProcessInfo processInfo : runningProcesses) {
                if (processInfo.importance == ActivityManager.RunningAppProcessInfo.IMPORTANCE_FOREGROUND) {
                    for (String activeProcess : processInfo.pkgList) {
                        if (activeProcess.equals(context.getPackageName())) {
                            isInBackground = false;
                        }
                    }
                }
            }
        } else {
            List<ActivityManager.RunningTaskInfo> taskInfo = am.getRunningTasks(1);
            ComponentName componentInfo = taskInfo.get(0).topActivity;
            if (componentInfo.getPackageName().equals(context.getPackageName())) {
                isInBackground = false;
            }
        }

        return isInBackground;
    }

通过向AndroidManifest添加权限解决了该问题。

<uses-permission android:name="android.permission.REAL_GET_TASKS" />