getRunningAppProcesses returns empty list on Android M(5.1.1)

前端 未结 3 447
花落未央
花落未央 2021-02-03 10:34

I just tested my app and CM, ATM Android Assistant, etc. All of them can not get the running process list but they works fine on pre OS version. So what\'s going on with Androi

3条回答
  •  时光说笑
    2021-02-03 11:09

    Another option is to use UsageStatsManager.

    UsageStatsManager mUsageStatsManager = (UsageStatsManager)getSystemService(Context.USAGE_STATS_SERVICE);
    long endTime = System.currentTimeMillis();
    long beginTime = endTime - 1000*60;
    
    // We get usage stats for the last minute
    List stats = mUsageStatsManager.queryUsageStats(UsageStatsManager.INTERVAL_DAILY, beginTime, endTime);
    
    // Sort the stats by the last time used
    if(stats != null) 
    {
        SortedMap mySortedMap = new TreeMap();
        for (UsageStats usageStats : stats) 
        {
            mySortedMap.put(usageStats.getLastTimeUsed(),usageStats);
        }
        if(mySortedMap != null && !mySortedMap.isEmpty()) 
        {
            topActivity =  mySortedMap.get(mySortedMap.lastKey()).getPackageName();
        }
    }
    

    In order for this to work, you need PACKAGE_USAGE_STATS permission. You can prompt the user to do this by opening the screen in settings:

    Intent usageAccessIntent = new Intent( Settings.ACTION_USAGE_ACCESS_SETTINGS );
    usageAccessIntent.addFlags( Intent.FLAG_ACTIVITY_NEW_TASK );
    startActivity( usageAccessIntent );
    

提交回复
热议问题