android adb 关机实现方式


   笔者遇到需要控制android emulator关机的问题,主要有以下几种方法实现:

第一种:

    Intent intent = new Intent(Intent.ACTION_REQUEST_SHUTDOWN);
    intent.putExtra(Intent.EXTRA_KEY_CONFIRM, false);
    intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
    startActivity(intent);

     这里需要注意的一点是,需要将frameworks.jar导入到eclipse工程,否则没有Intent.ACTION_REQUEST_SHUTDOWN这一项   

    frameworks.jar在源码目录地址为./out/target/product/generic/system/framework

第二种:

      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, boolean.class);
            // 调用shutdown()方法
            shutdown.invoke(oIPowerManager, false, true);

        } catch (Exception e) {
            Log.e("SystemStatusSetting", e.toString(), e);
        }
    }

      该方法是利用了反射机制调用PowerManagerService shutdown,PowerManager类没有提供关机的接口,而是通过IBinder与PowerManagerService 类进行通信。PowerManagerService调用Power 类来与下一层进行通信. PowerManagerService实现了shutdown接口,power服务实现了关机功能。 IPowerManager是AIDL文件自动生成的类,便于远程通信。IPowerManage.aidl文件目录framework/base/core/java/android/os/IPowerManage.aidl
IPowerManager实现了shutdown接口,所以,如果我们能够获得Power服务的IBinder,通过反射调用shutdown方法就能实现关机功能PowerManager提供了reboot接口可以直接调用PowerManager pManager=(PowerManager) getSystemService(Context.POWER_SERVICE);  //重启到fastboot模式                pManager.reboot("");

第三种:

        通过adb shell 登录后,发现system/bin 下面只有reboot命令,没有shutdown命令。经过研究发现可以通过reboot -p命令来实现关机,于是

        try{
                    Process process =Runtime.getRuntime().exec(new String[]{"su","-c","reboot -p"});  //关机
                    proc.waitFor();
                }catch(Exception e){
                    e.printStackTrace();
                }

      使用该方法需要注意的是,使用的Android设备必须已经root过

  • 3
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值