I use the following code to get the activity name of the foreground app in the variable foregroundTaskPackageName. It works on all OS versions between 4.1 t
Try this
public static boolean isForeground(Context context) {
ActivityManager manager = (ActivityManager)context.getSystemService(Context.ACTIVITY_SERVICE);
List tasks = manager.getRunningAppProcesses();
if(tasks.isEmpty())
return false;
for (ActivityManager.RunningAppProcessInfo task : tasks) {
if(context.getPackageName().equalsIgnoreCase(task.processName)){
return task.importance == ActivityManager.RunningAppProcessInfo.IMPORTANCE_FOREGROUND;
}
}
return false;
}