Search code examples
androidandroid-activitymanager

Detect current foreground android application


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"


Solution

  • This method is deprecated in Android 5, so for security reasons this method will return your package name if your app is in foreground, but no other apps. Since you are using Android 6, I guess this method is returning always the launcher package name to hide the actual foreground app.

    From documentation:

    List<ActivityManager.RunningTaskInfo> getRunningTasks (int maxNum)
    

    This method was deprecated in API level 21. As of LOLLIPOP, this method is no longer available to third party applications: the introduction of document-centric recents means it can leak person information to the caller. For backwards compatibility, it will still return a small subset of its data: at least the caller's own tasks, and possibly some other tasks such as home that are known to not be sensitive.