I want to implement some code lines that allow Android turn on/off screen like we quick turn on/off device by using Power button. Is there any way to do that?
-
Do you want to lock the device or turn it off? – cjds Dec 13 '12 at 02:49
-
The exactly what i want is recall LockScreen display. After turn screen off -> turn it on -> the LockScreen will be displayed. Do you have any suggestion? – Nguyen Dec 13 '12 at 02:54
-
If you are getting a runtime error I posted a solution – cjds Dec 13 '12 at 05:07
3 Answers
It seems you want to lock the device not turn it off. To lock the device its a simple code. Mentioned here
It uses device Policy Manager lockNow()
method
In case of a RuntimeError use the method described in this question to set permissions
Android DevicePolicyManager lockNow()
http://developer.android.com/reference/android/app/admin/DevicePolicyManager.html
To switch off the device:
This is not possible but you can reboot it using PowerManager
http://developer.android.com/reference/android/os/PowerManager.html#reboot
Note this requires REBOOT permission and OS may cancel it.
-
I am working on Android framework, so maybe there are some differences bwt application and framework. It still doesn't work. Anyway, thanks for your reply – Nguyen Dec 14 '12 at 09:18
You can use DevicePolicyManger.lockNow()
: http://developer.android.com/reference/android/app/admin/DevicePolicyManager.html#lockNow%28%29

- 12,448
- 10
- 74
- 118
-
After call lockNow(), it throw exception:E/AndroidRuntime( 1159): *** FATAL EXCEPTION IN SYSTEM PROCESS: WindowManagerPolicy E/AndroidRuntime( 1159): java.lang.NullPointerException – Nguyen Dec 13 '12 at 03:22
-
Yes, you can do with programming using below code, Note: This solution works only on rooted device
Shutdown:
try {
Process proc = Runtime.getRuntime()
.exec(new String[]{ "su", "-c", "reboot -p" });
proc.waitFor();
} catch (Exception ex) {
ex.printStackTrace();
}
Restart:
Same code, just use "reboot"
instead of "reboot -p"
.

- 6,331
- 4
- 51
- 81