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.
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]
You cannot do this from an ordinary SDK application. Only applications signed with the system firmware signing key can do this.
You could possibly use the PowerManager to make it reboot (this does not guarantee that it'll reboot - OS may cancel it):
http://developer.android.com/reference/android/os/PowerManager.html#reboot(java.lang.String)
It requires the REBOOT permission:
http://developer.android.com/reference/android/Manifest.permission.html#REBOOT
Can you also check your logcat when trying to enable/disable keyguard, and post what's there?
A much better solution is to run:
su -c am start -a android.intent.action.ACTION_REQUEST_SHUTDOWN
You can use a Process
for this.
If you have the sigOrSystem permission android.permission.SHUTDOWN you can raise the protected ACTION_REQUEST_SHUTDOWN Intent like this:
Intent intent = new Intent("android.intent.action.ACTION_REQUEST_SHUTDOWN");
intent.putExtra("android.intent.extra.KEY_CONFIRM", false);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(intent);
Note that prior to Android 4.0, this permission was signature only.