Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

Thanks!

like image 898
lage Avatar asked Dec 06 '14 09:12

lage


1 Answers

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.

like image 104
tzanou Avatar answered Sep 21 '22 01:09

tzanou