简体   繁体   English

有没有办法在Android中获取所有当前处于活动状态的应用程序?

[英]Is there a way to get all currently active apps in Android?

I need to lock other apps when they are opened by the user in some time period, but I don't want to implement a service that will check after every second that which app is opened and lock accordingly. 当用户在一段时间内打开其他应用程序时,我需要锁定它们,但是我不想实现一项服务,该服务将在每秒之后检查哪个应用程序已打开并相应地锁定。 I want that, somehow, Android will broadcast with active app information. 我希望Android以某种方式广播有效的应用程序信息。

Is it possible, and if yes, how? 有可能吗?如果可以,怎么办?

Call ActivityManager.getRunningAppProcesses() , It will give you the list of running apps.If you want to see the details then iterate through the ActivityManager.RunningAppProcessInfo objects. 调用ActivityManager.getRunningAppProcesses() ,它将为您提供正在运行的应用程序的列表。如果您想查看详细信息,请遍历ActivityManager.RunningAppProcessInfo对象。

you can also check if your app is in Background or not by: 您还可以通过以下方法检查您的应用是否在后台运行:

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

I want that, somehow, Android will broadcast with active app information. 我希望Android以某种方式广播有效的应用程序信息。

That does not exist. 那不存在。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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