关于android使用代码实现关机

使用以下方式进行关机操作,必须是在设备已经进行root后,否则无效,重要!重要!重要!

1、使用广播的方式进行关机操作

不root的话,权限异常  requires android.permission.SHUTDOWN

代码

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调用关机的方法

不root的话,权限异常  SecurityException: Neither user 10121 nor current process has android.permission.REBOOT.

代码

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,没有再写,你有兴趣的话,可以自己搞一下

©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容