此两项功能需要使用系统签名!
一、在AndroidMainfest.xml中添加android:sharedUserId="android.uid.system"和相应权限:
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
android:sharedUserId="android.uid.system"
package="xxx">
<uses-permission android:name="android.permission.SHUTDOWN" />
<uses-permission android:name="android.permission.REBOOT" />
二、代码如下:
public static void shutdownSys(Context context) { // 关机
Intent intent = new Intent();
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
intent.setAction("com.android.internal.intent.action.REQUEST_SHUTDOWN");
} else {
intent.setAction("android.intent.action.ACTION_REQUEST_SHUTDOWN");
}
intent.putExtra("android.intent.extra.KEY_CONFIRM", false);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
context.startActivity(intent);
}
public static void rebootSys(Context context) { // 重启
PowerManager pm = (PowerManager) context.getSystemService(Context.POWER_SERVICE);
pm.reboot("");
}
注意关机功能,在Android O版本或以上,需要使用REQUEST_SHUTDOWN,在Android O版本以下是使用ACTION_REQUEST_SHUTDOWN。
注:尝试过网上介绍的的反射调用和使用Runtime调用linux shell的方式,皆不行。实际运行时,使用反射调用方式,提示找不到shutdown方法,而使用Runtime执行shell的方式,则提示Cannot run program "su": error=13, Permission denied,是Android 5.0 Lollipop及以上版本已经不允许通过su方式获取root权限了。