使用以下方式进行关机操作,必须是在设备已经进行root后,否则无效,重要!重要!重要!
1、使用广播的方式进行关机操作
代码
String action ="com.android.internal.intent.action.REQUEST_SHUTDOWN";
if(Build.VERSION.SDK_INT <= Build.VERSION_CODES.N){
action ="android.intent.action.ACTION_REQUEST_SHUTDOWN";
}
Intent shutdown =new Intent(action);
shutdown.putExtra("android.intent.extra.KEY_CONFIRM",false);
shutdown.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
try {
startActivity(shutdown);
finish();
}catch(Exception e){
e.printStackTrace();
}
2、通过反射的方式进行关机操作
通过PowerManager源码你可以看到 有个IPowerManager的类实现了shutdown()的方法,下面就是通过反射获取IPowerManager调用关机的方法
代码
try {
Class ServiceManager = Class.forName("android.os.ServiceManager");
//获得ServiceManager的getService方法
Method getService = ServiceManager.getMethod("getService", java.lang.String.class);
//调用getService获取RemoteService
Object oRemoteService = getService.invoke(null,Context.POWER_SERVICE);
//获得IPowerManager.Stub类
Class cStub = Class.forName("android.os.IPowerManager$Stub");
//获得asInterface方法
Method asInterface = cStub.getMethod("asInterface", android.os.IBinder.class);
//调用asInterface方法获取IPowerManager对象
Object oIPowerManager = asInterface.invoke(null, oRemoteService);
//获得shutdown()方法
Method shutdown = oIPowerManager.getClass().getMethod("shutdown",boolean.class,java.lang.String.class,boolean.class);
//调用shutdown()方法
shutdown.invoke(oIPowerManager,false,null,true);
}catch (Exception e){
Log.i("sun","关机异常=="+e);
Throwable t = e.getCause();// 获取目标异常
t.printStackTrace();
}
还有一种方法就是操作系统文件,更是需要root,没有再写,你有兴趣的话,可以自己搞一下