简体   繁体   中英

How to check that application is running (Android>5.1)?

The code below works successfully on Android 4.4, but since android 5.1 getRunningAppProcesses () return only own process. How can I check if the application is running on 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;
}

What to use instead of getRunningAppProcesses () for Android 5.1 and above.

/** * Method checks if the app is in background or not */

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

The issue was resolved by adding permission to AndroidManifest.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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