Android代码中实现关机

2,588 阅读1分钟

想要在代码中实现关机需要 apk 有系统权限,要在 manifest 文件添加 android:sharedUserId=“android.uid.system”,还要有系统签名。

第一种方式

直接使用 adb shell 命令,调用 reboot 命令来关机

try {
    Runtime.getRuntime().exec("reboot -p"); //关机
} catch (IOException e) {
    e.printStackTrace();
}

第二种方式

调用 PowerManage 中的 shutdown 方法,但是该方法是隐藏的 API,通过反射即可调用,代码如下:

try {
    PowerManager pManager = (PowerManager) VfiServiceApp.getContext().getSystemService(Context.POWER_SERVICE);
    if (pManager != null) {
        Method method = pManager.getClass().getMethod("shutdown", boolean.class, String.class, boolean.class);
        method.invoke(pManager, false, null, false);
    }
} catch (Exception e) {
    e.printStackTrace();
}

第一种直接黑屏,第二种可以设置对话框,都为 false 的话直接出现关机对话框,不会直接黑屏