I am using Intent ACTION_USAGE_ACCESS_SETTINGS
in setting (Settings->Security->Apps with usage access
) to use UsageStatsManager
in the Lollipop version.
public static final int MY_PERMISSIONS_REQUEST_PACKAGE_USAGE_STATS = 1;
if(!hasPermission()){
startActivityForResult(
new Intent(Settings.ACTION_USAGE_ACCESS_SETTINGS),
MY_PERMISSIONS_REQUEST_PACKAGE_USAGE_STATS);
}
First, onCreate() will check the permission for the app. and turn on the Intent if the app has no permission (does not check)
@TargetApi(Build.VERSION_CODES.LOLLIPOP)
private boolean hasPermission() {
try {
PackageManager packageManager = getApplicationContext().getPackageManager();
ApplicationInfo applicationInfo = packageManager.getApplicationInfo(getApplicationContext().getPackageName(), 0);
AppOpsManager appOpsManager = (AppOpsManager) getApplicationContext().getSystemService(Context.APP_OPS_SERVICE);
int mode = appOpsManager.checkOpNoThrow(AppOpsManager.OPSTR_GET_USAGE_STATS, applicationInfo.uid, applicationInfo.packageName);
return (mode == AppOpsManager.MODE_ALLOWED);
} catch (PackageManager.NameNotFoundException e) {
return false;
}
}
My question is that I want to close the setting window, if the user chooses (check) in target app, otherwise, it will show a message about application name to guide the chosen of the user. How can I do it? Thank you. I think it will do in onActivityResult
function
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == MY_PERMISSIONS_REQUEST_PACKAGE_USAGE_STATS){
...
}
}
I refer the link Check if my application has usage access enabled, but it just checks enable of the app.