反射技术实现关机

来源:互联网 发布:神经官能症知乎 编辑:程序博客网 时间:2024/06/06 12:53
这里介绍我自己的方法。

1. power服务实现了关机功能
framework/base/services/java/com/android/server/power/PowerManagerService.java
   
    /**
     * Shuts down the device.
     *
     * @param confirm If true, shows a shutdown confirmation dialog.
     * @param wait If true, this call waits for the shutdown to complete and does not return.
     */
    @Override // Binder call
    public void shutdown(boolean confirm, boolean wait) {
        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.REBOOT, null);

        final long ident = Binder.clearCallingIdentity();
        try {
            shutdownOrRebootInternal(true, confirm, null, wait);
        } finally {
            Binder.restoreCallingIdentity(ident);
        }
    }


2. PowerManager提供了reboot等接口,没有提供shutdown接口。
若是重启,实现就很简单:
   PowerManager pm = (PowerManager)this.getSystemService(Context.POWER_SERVICE);
   pm.reboot();
但是shutdown没有实现,PowerManager的实现通过IPowerManager来调用Power服务的接口。
IPowerManager是AIDL文件自动生成的类,便于远程通信。IPowerManage.aidl文件目录framework/base/core/java/android/os/IPowerManage.aidl

3. IPowerManager实现了shutdown接口,这里只要获得Power服务的IBinder,通过反射调用shutdown方法就能实现关机功能。
ServiceManager管理着系统的服务程序,它保存着所有服务的IBinder,通过服务名就能获取到这个服务的IBinder。
而ServiceManager这个类也是HIDE的,也需要反射进行调用。


代码实现:
[java] view plaincopyprint?
  1. try {  
  2.             
  3.           //获得ServiceManager类  
  4.           Class<?> ServiceManager = Class  
  5.              .forName("android.os.ServiceManager");  
  6.             
  7.           //获得ServiceManager的getService方法  
  8.           Method getService = ServiceManager.getMethod("getService", java.lang.String.class);  
  9.             
  10.           //调用getService获取RemoteService  
  11.           Object oRemoteService = getService.invoke(null,Context.POWER_SERVICE);  
  12.             
  13.           //获得IPowerManager.Stub类  
  14.           Class<?> cStub = Class  
  15.              .forName("android.os.IPowerManager$Stub");  
  16.           //获得asInterface方法  
  17.           Method asInterface = cStub.getMethod("asInterface", android.os.IBinder.class);  
  18.           //调用asInterface方法获取IPowerManager对象  
  19.           Object oIPowerManager = asInterface.invoke(null, oRemoteService);  
  20.           //获得shutdown()方法  
  21.           Method shutdown = oIPowerManager.getClass().getMethod("shutdown",boolean.class,boolean.class);  
  22.           //调用shutdown()方法  
  23.           shutdown.invoke(oIPowerManager,false,true);             
  24.       
  25. catch (Exception e) {           
  26.      Log.e(TAG, e.toString(), e);          

原创粉丝点击