lage lage - 1 year ago 200
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.


Answer Source

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

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download