Android 5.1.1 及更高版本 - getRunningAppProcesses() 仅返回我的应用程序包

标签 android android-6.0-marshmallow

Google 似乎终于关闭了获取当前前台应用程序包的所有大门。

Lollipop 更新后,杀死了getRunningTasks(int maxNum)感谢this answer ,我用这段代码获取Lollipop以来的前台应用包:

final int PROCESS_STATE_TOP = 2;
RunningAppProcessInfo currentInfo = null;
Field field = null;
try {
    field = RunningAppProcessInfo.class.getDeclaredField("processState");
} catch (Exception ignored) { 
}
ActivityManager am = (ActivityManager) this.getSystemService(Context.ACTIVITY_SERVICE);
List<RunningAppProcessInfo> appList = am.getRunningAppProcesses();
for (RunningAppProcessInfo app : appList) {
    if (app.importance == RunningAppProcessInfo.IMPORTANCE_FOREGROUND &&
        app.importanceReasonCode == 0 ) {
        Integer state = null;
        try {
            state = field.getInt( app );
        } catch (Exception ignored) {
        }
        if (state != null && state == PROCESS_STATE_TOP) {
            currentInfo = app;
            break;
        }
    }
}
return currentInfo;

Android 5.1.1 及更高版本 (6.0 Marshmallow) 似乎被杀死了 getRunningAppProcesses()也是。它现在返回您自己的应用程序包的列表。


UsageStatsManager

我们可以使用新的 UsageStatsManager API 作为 described here但它不适用于所有应用程序。一些系统应用会返回相同的包

com.google.android.googlequicksearchbox

AccessibilityService(2017 年 12 月:将被 Google 禁止使用)

一些应用程序使用 AccessibilityService(如 seen here),但它有一些缺点。


还有其他方法可以获取当前运行的应用包吗?

最佳答案

要获取 Android 1.6 - Android 6.0 上正在运行的进程列表,您可以使用我写的这个库:https://github.com/jaredrummler/AndroidProcesses库读取/proc 以获取进程信息。

Google 对 Android Nougat 中的/proc 的访问进行了严格限制。要获取 Android Nougat 上正在运行的进程列表,您需要使用 UsageStatsManager 或拥有 root 访问权限。

单击以前的替代解决方案的编辑历史记录。

关于Android 5.1.1 及更高版本 - getRunningAppProcesses() 仅返回我的应用程序包,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30619349/

相关文章:

java - 使用 firebase ValueEventListener 检测值变化

android - RecyclerView 的第一项丢失

android - 棉花糖存储和图库使用的读写权限

android m Preview 3 应用程序在权限 CONNECTIVITY_INTERVAL 的情况下崩溃

android - 打瞌睡模式和应用程序待机

java - 使用 SQLite 填充饼图

java - 使用 AsyncTask 编辑 Fragment UI 项目

android - 单击编辑按钮后如何使edittext可编辑

android - Android Marshmallow 上的白色通知图标

android - 在 Nexus 7 Marshmallow 上初始化 AudioRecorder