I would like to write an android service that checks every 5 seconds for the foreground application currently running e.g. if the user is currently using Chrome, it should give me Chrome as the running app. When the user switches to Google Maps, it should tell me Google Maps after 5 seconds.
I have tried to use the following code to get the current foreground application.
ActivityManager.RunningTaskInfo foregroundTaskInfo = mActivityManager.getRunningTasks(1).get(0);
String foregroundTaskPackageName = foregroundTaskInfo.topActivity.getPackageName();
The code works well when the application having my service is in the foreground, it returns the package name of my application but when I switch to another application, it gives me "com.sec.android.app.launcher"