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!
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With