It seems Google finally closed all doors for getting the current foreground application package.
After the Lollipop update, which killed getRunningTasks(int maxNum)
and thanks to this answer, I used this code to get the foreground application package since 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 and above (6.0 Marshmallow), it seems, killed getRunningAppProcesses()
as well. It now returns a list of your own application package.
UsageStatsManager
We can use the new UsageStatsManager
API as described here but it doesn't work for all applications. Some system applications will return the same package
com.google.android.googlequicksearchbox
AccessibilityService (December 2017: Going to be banned for use by Google)
Some applications use AccessibilityService
(as seen here) but it has some disadvantages.
Is there another way of getting the current running application package?
UsageStatsManager
, did you have the same problems with an accessibility service orgetRunningAppProcesses
in Android L? – Dosserps
in a shell and the policy is"fg"
and the contents of/proc/[pid]/oom_adj_score
equals0
then the app is the foreground application. Unfortunately, it seems/proc/[pid]/oom_adj_score
is no longer readable on Android 6.0. gist.github.com/jaredrummler/7d1498485e584c8a120e – Phung