Notice how the lines:
Intent it = new Intent(DevicePolicyManager.ACTION_ADD_DEVICE_ADMIN);
it.putExtra(DevicePolicyManager.EXTRA_DEVICE_ADMIN, new ComponentName(this, YourAdminReceiver.class));
startActivityForResult(it, 0);
can be skipped. If you do not want your users to allow the app to lock the screen there is the alternative way:
adb shell dpm set-device-owner com.package/.YourAdminReceiver
Now what does this have to do with the SecurityException the OP was encountering ?
Well, I already had the device owner set to com.package/.YourAdminReceiver
via the adb shell way, but for different purposes than screen locking. When I have added the <force-lock>
tag to my device-admin.xml:
<uses-policies>
<limit-password />
<reset-password />
<force-lock />
</uses-policies>
I was naturally expecting my locknow()
API call to work, but instead it hasn't. I got the SecurityException
just as OP did. Strange, given that my app was already the admin and owner of the device. I have made it work by unsetting from the device owner role, uninstalling it and then reinstalling it. Be advised that once set as a device owner via adb shell, an app can only be unset from that role from code:
// mDpm.clearDeviceOwnerApp(getPackageName());
// mDpm.removeActiveAdmin(deviceAdmin);