11

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?

Nguyen
  • 2,019
  • 1
  • 24
  • 31

3 Answers3

2

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.

Community
  • 1
  • 1
cjds
  • 8,268
  • 10
  • 49
  • 84
  • 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
2

You can use DevicePolicyManger.lockNow(): http://developer.android.com/reference/android/app/admin/DevicePolicyManager.html#lockNow%28%29

Josh
  • 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
  • after that, the device is forced to reboot – Nguyen Dec 13 '12 at 03:24
0

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".

Yogesh Rathi
  • 6,331
  • 4
  • 51
  • 81