I have been using this Stackoverflow answer to check if the user has already granted the "Usage Stats' permission:
boolean granted = false;
AppOpsManager appOps = (AppOpsManager) this
.getSystemService(Context.APP_OPS_SERVICE);
int mode = appOps.checkOpNoThrow(AppOpsManager.OPSTR_GET_USAGE_STATS,
android.os.Process.myUid(), this.getPackageName());
if (mode == AppOpsManager.MODE_DEFAULT) {
granted = (this.checkCallingOrSelfPermission(android.Manifest.permission.PACKAGE_USAGE_STATS) == PackageManager.PERMISSION_GRANTED);
} else {
granted = (mode == AppOpsManager.MODE_ALLOWED);
}
if (!granted) {
activate.setChecked(false);
new AlertDialog.Builder(this)
.setTitle("First enable permission!")
.setMessage("In order to use this app, you must enable the Usage permission")
.setPositiveButton("Enable", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialogInterface, int i) {
Intent intent = new Intent(Settings.ACTION_USAGE_ACCESS_SETTINGS);
startActivity(intent);
}
}).show();
}
The preceding code works fine on my 7.0 device, but when I emulated a 4.4 Kitcat device, I got the following error:
java.lang.IllegalArgumentException: Unknown operation string: android:get_usage_stats
at android.app.AppOpsManager.strOpToOp(AppOpsManager.java:855)
at android.app.AppOpsManager.checkOpNoThrow(AppOpsManager.java:885)
at com.curlybrace.ruchir.keepfocusneverprocrastinateagain.MainActivity.checkPermissions(MainActivity.java:714)
at com.curlybrace.ruchir.keepfocusneverprocrastinateagain.MainActivity.activated(MainActivity.java:639)
at com.curlybrace.ruchir.keepfocusneverprocrastinateagain.MainActivity$4.onCheckedChanged(MainActivity.java:241)
at android.widget.CompoundButton.setChecked(CompoundButton.java:127)
at android.widget.Switch.setChecked(Switch.java:666)
at android.widget.CompoundButton.toggle(CompoundButton.java:87)
at android.widget.CompoundButton.performClick(CompoundButton.java:99)
at android.view.View$PerformClick.run(View.java:18422)
at android.os.Handler.handleCallback(Handler.java:733)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:136)
at android.app.ActivityThread.main(ActivityThread.java:5001)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:515)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:785)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:601)
at dalvik.system.NativeStart.main(Native Method)
caused by this line int mode = appOps.checkOpNoThrow(AppOpsManager.OPSTR_GET_USAGE_STATS
. It seems as if no one else has experienced this issue, so I'm not sure what the problem here is. All help is appreciated.
UsageStatsManager
was added in API Level 21.OPSTR_GET_USAGE_STATS
was also added in API Level 21. You will not be able to use these on API Level 19.