At the moment I use this code (in my background service) to determine the current foreground app:
List<ActivityManager.RunningTaskInfo> runningTask = activityManager.getRunningTasks(1);
ActivityManager.RunningTaskInfo ar = runningTask.get(0);
return ar.topActivity.getPackageName();
The Problem is that it returns me the right foreground app in 99% of the cases but sometimes it returns the false app. As an example when I use the gallery and then return to the launcher sometimes it reports the launcher and sometimes it further reports the gallery! For my app it's really important to determine the RIGHT foreground app. Is there any better (100% reliable) solution available?
Thanks in advance!