贴上实现代码:
public void shutdown(){ try { //获得ServiceManager类 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,String.class,boolean.class); //调用shutdown()方法 shutdown.invoke(oIPowerManager,false,"userrequested",true); } catch (Exception e) { Log.e(TAG, e.toString(), e); }
这里我在网上参考的4.4的居多,所以在关机函数参数上有所差异,导致异常找不到shutdown方法,通过查看源码,添加参数即可。
2.<uses-permission android:name="android.permission.REBOOT"/> //添加reboot权限
3.android:sharedUserId="android.uid.system"
这些操作执行之后再系统签名之后即可。