To begin with see here:
To control this policy, the device admin must have a "force-lock" tag
in the "uses-policies" section of its meta-data.
The calling device admin must have requested USES_POLICY_FORCE_LOCK to
be able to call this method; if it has not, a security exception will
be thrown.
Depending from the code you got, here's a pretty nice explanation of what can be wrong in your case (of course any code provided here will be of use!).
I've heard on several occasions, that calling twice the code DevicePolicyManager.lockNow()
will do the trick and here's one way of doing that:
mDPM = (DevicePolicyManager)getApplicationContext().getSystemService("device_policy");
Handler handlerUI = new Handler();
handlerUI.postDelayed(new Runnable() {
@Override
public void run() {
mDPM.lockNow();
}
}, 200);
finish();
mDPM.lockNow();
Here I found a more elaborate version of the same thing:
Android DevicePolicyManager lockNow() problem
public class SMSMessagingActivity extends Activity {
/** Called when the activity is first created. */
public static DevicePolicyManager mDPM;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
mDPM = (DevicePolicyManager)getSystemService(Context.DEVICE_POLICY_SERVICE);
}
public static void LockNow(){
mDPM.lockNow();
}
}
ComponentName devAdminReceiver; // this would have been declared in your class body
// then in your onCreate
mDPM = (DevicePolicyManager)getSystemService(Context.DEVICE_POLICY_SERVICE);
devAdminReceiver = new ComponentName(context, deviceAdminReceiver.class);
//then in your onResume
boolean admin = mDPM.isAdminActive(devAdminReceiver);
if (admin)
mDPM.lockNow();
else Log.i(tag,"Not an admin");
Let's hope that the last workaround will work correctly.
Cheers