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.
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.
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.
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.
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]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With