Cannot get foreground activity name in Android Lollipop 5.0 only

user1406716 picture user1406716 · Nov 23, 2014 · Viewed 23k times · Source

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 to 4.4, but does not work in Android 5.0 Lollipop.

Can anyone help with what has changed in 5.0 Lollipop? In Lollipop - the text I get for foregroundTaskPackageName is just 'Launcher3'. I am using the Genymotion Emulator.

ActivityManager am = (ActivityManager) getSystemService(ACTIVITY_SERVICE);
RunningTaskInfo foregroundTaskInfo = am.getRunningTasks(1).get(0); // get
                                                                        // list
                                                                        // of
                                                                        // running
                                                                        // tasks
String foregroundTaskAppName = null;
String foregroundTaskPackageName = foregroundTaskInfo.topActivity
                .getPackageName();

Answer

Mert picture Mert · Jan 6, 2015

This works for me on Lollipop (21):

    ActivityManager manager = (ActivityManager)mContext.getSystemService(Context.ACTIVITY_SERVICE);

    List<ActivityManager.RunningAppProcessInfo> tasks = manager.getRunningAppProcesses();

    Log.i("current_app",tasks.get(0).processName);