Android M: How can I get the current foreground activity package name(from a service)

Mr.Clear picture Mr.Clear · Nov 7, 2015 · Viewed 8.8k times · Source

It is easy to get a list of running tasks from the ActivityManager service on Android L, and the current active task is returned first. But it don't work on Android M any more, the return list only contains my app task. Is there any way to settle it?

My code:

List<ActivityManager.RunningAppProcessInfo> runningAppProcessInfos = activityManager.getRunningAppProcesses();
for (int i = 0; i < runningAppProcessInfos.size(); i++) {
    ActivityManager.RunningAppProcessInfo runningAppProcessInfo = runningAppProcessInfos.get(i);
    if (runningAppProcessInfo.importance == ActivityManager.RunningAppProcessInfo.IMPORTANCE_FOREGROUND) {
        return runningAppProcessInfo.pkgList[0];
    }
}

Answer

Vishal Butani picture Vishal Butani · Nov 20, 2015

you can use below code and get the current foreground activity package name.

   if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.LOLLIPOP) {
            UsageStatsManager usm = (UsageStatsManager) getSystemService("usagestats");
            long time = System.currentTimeMillis();
            List<UsageStats> appList = usm.queryUsageStats(UsageStatsManager.INTERVAL_DAILY,
                            time - 1000 * 1000, time);
                    if (appList != null && appList.size() > 0) {
                        SortedMap<Long, UsageStats> mySortedMap = new TreeMap<Long, UsageStats>();
                        for (UsageStats usageStats : appList) {
                            mySortedMap.put(usageStats.getLastTimeUsed(),
                                    usageStats);
                        }
                        if (mySortedMap != null && !mySortedMap.isEmpty()) {
                            currentApp = mySortedMap.get(
                                    mySortedMap.lastKey()).getPackageName();
                        }
                    }
        } else {
                ActivityManager am = (ActivityManager) getBaseContext().getSystemService(ACTIVITY_SERVICE);
                currentApp = am.getRunningTasks(1).get(0).topActivity .getPackageName(); 

        }

Edit

Add this permission in to Manifest file.

<uses-permission android:name="android.permission.GET_TASKS" /> 
<uses-permission android:name="android.permission.PACKAGE_USAGE_STATS" tools:ignore="ProtectedPermissions" />

Note

Make sure you need to configure custom setting in your device to obtain the output you can config it with Setting > Security > Apps with usage access > Then enable your app permission