DUPLICATE WARNING: this problem deals with details of Android API, suitable for calling both from some frontend and services, there are many similar threads on SO, but focused only on frontends.
Problem
I would like to turn on keyguard programmatically, so for example user clicks a button in my app and the phone gets locked (to use phone user has to unlock it first).
The catch is -- I would like to find rock-solid way, that works in every valid case.
Attempts
I tried:
lockNow
withDevicePolicyManager
-- when the screen is off (but phone is not locked) this call is ignored (i.e. the keyguard is not activated)reenableKeyguard
withKeyguardManager.KeyguardLock
-- the call to the method is ignored in every possible casegoToSleep
withPowerManager
-- I cannot call it, because of the problem with permission, it requiresDEVICE_POWER
despite I already have this permission set
So far I pursue the first way (lockNow
) with extra hacks that somehow deal with the case when the screen is off, but it extremely ugly, thus I am hoping there is some straightforward way.