想要在代码中实现关机需要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的话直接出现关机对话框,不会直接黑屏