androidandroid-5.0-lollipopusage-statistics

How can I find out if my app has usage stats access?


Since Android Lollipop there's an API for accessing app usage stats. Your app must be granted those permissions. Redirecting to those settings using Settings.ACTION_USAGE_ACCESS_SETTINGS, how do I know the user granted those permissions so I can stop redirecting?


Solution

  • you can simply query usagestats with daily interval and end time the current time and if nothing is returned this means the user hasn’t granted permissions

    @TargetApi(Build.VERSION_CODES.LOLLIPOP)
    public boolean doIHavePermission(){
    
    
        final UsageStatsManager usageStatsManager = (UsageStatsManager) context.getSystemService(Context.USAGE_STATS_SERVICE);
        final List<UsageStats> queryUsageStats = usageStatsManager.queryUsageStats(UsageStatsManager.INTERVAL_DAILY, 0,  System.currentTimeMillis());
    
        return !queryUsageStats.isEmpty();
    }
    

    Daily interval with start date 0 and end date the current time must at least return todays usage.So it will be empty only if permissions are not granted.