I\'m trying to get app-launched statistics, and on Lollipop it\'s possible by using the UsageStatsManager class, as such (original post here):
m
The extra check in Chris Li's answer is unnecessary unless you're developing a system app.
When an app is first installed and the user hasn't touched the app's usage access permission, then checkOpNoThrow() returns MODE_DEFAULT.
Chris says we then need to check if the app has the PACKAGE_USAGE_STATS manifest permission:
if (mode == AppOpsManager.MODE_DEFAULT) {
granted = (context.checkCallingOrSelfPermission(Manifest.permission.PACKAGE_USAGE_STATS) == PackageManager.PERMISSION_GRANTED);
} else {
granted = (mode == AppOpsManager.MODE_ALLOWED);
}
However, unless your app is a system app, checking this permission always returns PERMISSION_DENIED because it's a signature permission. So you can simplify the code down to this:
if (mode == AppOpsManager.MODE_DEFAULT) {
granted = false;
} else {
granted = (mode == AppOpsManager.MODE_ALLOWED);
}
Which you can then simplify down to this:
granted = (mode == AppOpsManager.MODE_ALLOWED);
Which brings us back to the original, simpler solution:
AppOpsManager appOps = (AppOpsManager) context.getSystemService(Context.APP_OPS_SERVICE);
int mode = appOps.checkOpNoThrow(AppOpsManager.OPSTR_GET_USAGE_STATS, Process.myUid(), context.getPackageName());
boolean granted = (mode == AppOpsManager.MODE_ALLOWED);
Tested and verified in Android 5, 8.1 and 9.