-2

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.

Andrew Efremov
  • 423
  • 5
  • 12
  • 4
    Possible duplicate of [How can I check the system version of Android?](https://stackoverflow.com/questions/3093365/how-can-i-check-the-system-version-of-android) – Murat Karagöz Oct 10 '17 at 09:40
  • The question is how to determine the list of running processes in Android 5.1 and above? What to use instead of getRunningAppProcesses()? – Andrew Efremov Oct 10 '17 at 09:46
  • This is not a duplicate, an implementation issue, not a version check!!!! – Andrew Efremov Oct 10 '17 at 09:54

1 Answers1

2

/** * 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" />  
Akshay Chopde
  • 670
  • 4
  • 10