As MKY mentioned, getRunningTasks()
method does not work for getting the current application in Lollipop.
As sunxin8086 wrote, the one way for getting the running applications is by using getRunningAppsProcesses()
method. However, the condition info.importance == IMPORTANCE_FOREGROUND
can not determine the current app uniquely.
The better approach to determine the current foreground application may be checking the processState
field in RunningAppProcessInfo
object. This field is a hidden field, but you can see it in the RunningAppProcessInfo
class. If this value is ActivityManager.PROCESS_STATE_TOP
(which is also
hidden static constant), the process is the current foreground process.
For example the code is
final int PROCESS_STATE_TOP = 2;
ActivityManager.RunningAppProcessInfo currentInfo = null;
Field field = null;
try {
field = ActivityManager.RunningAppProcessInfo.class.getDeclaredField("processState");
} catch (Exception ignored) {
}
ActivityManager am = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
List<ActivityManager.RunningAppProcessInfo> appList = am.getRunningAppProcesses();
for (ActivityManager.RunningAppProcessInfo app : appList) {
if (app.importance == ActivityManager.RunningAppProcessInfo.IMPORTANCE_FOREGROUND
&& app.importanceReasonCode == ActivityManager.RunningAppProcessInfo.REASON_UNKNOWN) {
Integer state = null;
try {
state = field.getInt(app);
} catch (Exception e) {
}
if (state != null && state == PROCESS_STATE_TOP) {
currentInfo = app;
break;
}
}
}
return currentInfo;
Note: processState
field does not exist in pre-Lolipop. Please check that Build.VERSION.SDK_INT >= 21
before running the above code. The above code works only for Lollipop+.
The other approach, by Gaston (which is quite different), and the meaning of 'current application' is slightly different from this approach.
Please choose one for your purpose.
[EDIT]
As Sam pointed out, I modified START_TASK_TO_FRONT
by PROCESS_STATE_TOP
. (Both values are 2)
[EDIT2]
Sam has a new find! To determine the foreground application uniquely, one more
condition
process.importanceReasonCode == 0
is necessary. The above code has been updated. Thanks!