看起来谷歌最终关闭了获取当前前台应用程序包的所有途径。
在Lollipop更新后,getRunningTasks(int maxNum)
已经失效,幸运的是有这个答案,我使用以下代码从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,如这里所述,但它并不适用于所有应用程序。一些系统应用程序将返回相同的包名。
com.google.android.googlequicksearchbox
AccessibilityService (2017年12月起被 Google 禁止使用)
一些应用程序使用AccessibilityService
(如此处所示),但它具有一些缺点。
是否有另一种方法可以获取当前正在运行的应用程序包?
ps
命令并解析输出,策略为“fg”,且/proc/[pid]/oom_adj_score
的内容等于0
,则该应用程序是前台应用程序。不幸的是,在Android 6.0上似乎无法读取/proc/[pid]/oom_adj_score
。https://gist.github.com/jaredrummler/7d1498485e584c8a120e - Jared Rummler