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

后端 未结 2 1567
無奈伤痛
無奈伤痛 2021-01-06 01:45

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 m

2条回答
  •  既然无缘
    2021-01-06 02:22

    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 appList = usm.queryUsageStats(UsageStatsManager.INTERVAL_DAILY,
                                time - 1000 * 1000, time);
                        if (appList != null && appList.size() > 0) {
                            SortedMap mySortedMap = new TreeMap();
                            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.

     
    
    

    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

提交回复
热议问题