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

后端 未结 2 1555
無奈伤痛
無奈伤痛 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<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

    0 讨论(0)
  • 2021-01-06 02:33

    Please try this lines in Android M. This worked for me

    String packageName =  ProcessManager.getRunningForegroundApps(getApplicationContext()).get(0).getPackageName();
    

    check below link for other android platform support.

    https://stackoverflow.com/a/36660429/4554069

    0 讨论(0)
提交回复
热议问题