3

在 Marshmallow 中,即使应用程序不在 backgounnd 和 foreground 中。我得到“应用程序正在运行”。我使用的代码是

ActivityManager activityManager = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
    List<ActivityManager.RunningAppProcessInfo> appProcesses = activityManager.getRunningAppProcesses();
for (int i = 0; i < appProcesses.size(); i++) {
        if (appProcesses.get(i).processName.equals("com.alive.moraribapuapp")) {
            Log.d(TAG, "com.alive.moraribapuapp is true(running)");

            return true;
        } else {
            Log.d(TAG, "com.alive.moraribapuapp is false(Not running)");
            return false;
        }
    }

即使应用程序在棉花糖中关闭,这也给了我真实的感觉。

4

1 回答 1

4

rashad.z,问题解决了,我们必须手动检查 aap in 是否是前台。

 private boolean isAppOnForeground(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;
        }
    }

    Log.d("MyGcmListenerService", "" + isInBackground);
    return isInBackground;
}
于 2016-05-03T07:33:11.703 回答