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
You need to use the new UsageStatsManager
and call its queryUsageStats
method to get the history of activities launched.
Please note that the user will be required to provide access to usage stat on the device settings at Security->Apps with usage access.
Links:
UsageStatsManager documentation
queryUsageStats method documentation