lage lage - 5 months ago 91
Android Question

Android Lollipop know if app as Usage Stats access

Since Android Lollipop, we have now an API for accessing apps usage stats. However, your app must be granted those permissions by the user.

I know that for redirecting the user to those settings using Settings.ACTION_USAGE_ACCESS_SETTINGS.

Now, my question is how do you know the user has granted you those permissions so that you can stop redirecting him to the settings.



you can simply query usagestats with daily interval and end time the current time and if nothing is returns this means the user hasnt granted permissions

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