Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Programmatically switching off Android phone

Can we switch off an Android phone programmatically?

I am using following snippet but it didn't work for me.

KeyguardManager keyguardManager = (KeyguardManager) getSystemService(Activity.KEYGUARD_SERVICE);  KeyguardLock lock = keyguardManager.newKeyguardLock(KEYGUARD_SERVICE);   lock.disableKeyguard(); // to disable  lock.reenableKeygaurd();// to enable 

and I used the permission also.

like image 679
Sri Sri Avatar asked Sep 19 '10 11:09

Sri Sri


People also ask

How to switch off android phone programmatically?

The PowerManager is one step better, but it sets the device into sleep mode, instead of a complete shutdown: PowerManager pm = (PowerManager)getSystemService(Service. POWER_SERVICE); pm. goToSleep(SystemClock.

How do I force my Android phone to turn off?

Force shutdown the device.Press and hold your Android device's Power button and the Volume Down key for at least 5 seconds or until the screen shuts down.

How do I prevent an Android device from going to sleep programmatically?

Using android:keepScreenOn="true" is equivalent to using FLAG_KEEP_SCREEN_ON . You can use whichever approach is best for your app. The advantage of setting the flag programmatically in your activity is that it gives you the option of programmatically clearing the flag later and thereby allowing the screen to turn off.


1 Answers

As CommonsWare already said that this is not possible in an Ordinary SDK Application. You need to sign your app with the System Firmware Key. But it's possible for your app with Root privileges. Try using the following code (if you have SU access):

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


[On an other note: I read somewhere that these commands do not work on Stock HTC ROMs, but haven't confirmed myself]

like image 75
Sheharyar Avatar answered Sep 23 '22 12:09

Sheharyar