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
i have created a class that uses /system/bin/toolbox command to identify processes and then identifies visible application.
Need to add identifies system apps with no UI and android launchers.