Is there an alternative for getRunningTask API

前端 未结 2 1593
小蘑菇
小蘑菇 2020-12-02 16:18

I was using getRunningTask API in one of my application to find the Foreground application. This API has been deprecated since Lollipop. After this deprecation, I preferred

2条回答
  •  抹茶落季
    2020-12-02 16:37

    Based on the answer to this question

    String getTopPackage(){
        long ts = System.currentTimeMillis();
        UsageStatsManager mUsageStatsManager = (UsageStatsManager)getSystemService("usagestats");
        List usageStats = mUsageStatsManager.queryUsageStats(UsageStatsManager.INTERVAL_BEST, ts-1000, ts);
        if (usageStats == null || usageStats.size() == 0) {
            return NONE_PKG;
        }
        Collections.sort(usageStats, mRecentComp);
        return usageStats.get(0).getPackageName();
    }
    

    This is the mRecentComp:

    static class RecentUseComparator implements Comparator {
    
        @Override
        public int compare(UsageStats lhs, UsageStats rhs) {
            return (lhs.getLastTimeUsed() > rhs.getLastTimeUsed()) ? -1 : (lhs.getLastTimeUsed() == rhs.getLastTimeUsed()) ? 0 : 1;
        }
    }
    

    This permission is needed:

    
    

    And you will need user authorization to request the stats, use this to direct the user to the settings page:

    Intent intent = new Intent(Settings.ACTION_USAGE_ACCESS_SETTINGS);
    startActivity(intent);
    

    And you can check if you already have permission like this:

    public static boolean needPermissionForBlocking(Context context) {
        try {
            PackageManager packageManager = context.getPackageManager();
            ApplicationInfo applicationInfo = packageManager.getApplicationInfo(context.getPackageName(), 0);
            AppOpsManager appOpsManager = (AppOpsManager) context.getSystemService(Context.APP_OPS_SERVICE);
            int mode = appOpsManager.checkOpNoThrow(AppOpsManager.OPSTR_GET_USAGE_STATS, applicationInfo.uid, applicationInfo.packageName);
            return  (mode != AppOpsManager.MODE_ALLOWED);
        } catch (PackageManager.NameNotFoundException e) {
            return true;
        }
    }
    

提交回复
热议问题