Android 使用反射调用自定义AIDL **.Stub.asInterface(IBinder obj)、反射实现关机shutdown

自定义AIDL调用

有时根据项目需要会增加系统没有的AIDL文件,如:
新增 com.android.internal.telephony.IVideoTelephony;

不使用反射时的调用方式如下(需依赖系统编译才能通过):

private boolean isVTCall(){
try{
IVideoTelephony vtInterface = null;
vtInterface = IVideoTelephony.Stub.asInterface(checkService("videophone"));
if(null != vtInterface){
if(vtInterface.isVtActive())
return true;o
}
}
catch(Exception e){}
return false;
}

----------------

private IBinder checkService(String name){
IBinder iBinder = null;
try{
Class<?> clz = Class.forName("android.os.ServiceManager");
Method checkService = clz.getMethod("checkService", String.class);
checkService.setAccessible(true);
iBinder = (IBinder)checkService.invoke(null, name);
}
catch(Exception e) {}
return iBinder;
}

使用反射调用

private boolean isVtActive(){
boolean isVtActive = false;
try{
Class<?> clz = Class.forName("com.android.internal.telephony.IVideoTelephony$Stub");
Method asInterface = clz.getDeclaredMethod("asInterface", IBinder.class);
Object IVideoTelephony = asInterface.invoke(null, checkService("videophone"));
Method isVtActiveMethod = IVideoTelephony.getClass().getDeclaredMethod("isVtActive",null);
isVtActive = (Boolean)isVtActiveMethod.invoke(IVideoTelephony, null);
}
catch(Exception e){}
return isVtActive;
}

代码解析:
1. 首先通过Class 加载”com.android.internal.telephony.IVideoTelephony$Stub”内部类;
2. 接着调用”asInterface”方法生成Object IVideoTelephony实例;
3. 然后获取”isVtActive”方法,通过invoke将实例IVideoTelephony传入并获取返回值即可

通过反射实现关机

 public static void shutDown(){
        try {
            Class<?> clz = Class.forName("android.os.ServiceManager");
            Method getService = clz.getMethod("getService", String.class);
            Object powerService = getService.invoke(null, Context.POWER_SERVICE);
            Class<?> cStub =  Class.forName("android.os.IPowerManager$Stub");
            Method asInterface = cStub.getMethod("asInterface", IBinder.class);
            Object IPowerManager = asInterface.invoke(null, powerService);
            Method shutDown = IPowerManager.getClass().getMethod("shutdown", boolean.class, boolean.class);
            shutDown.invoke(IPowerManager, false,true);
        } catch (Exception e) {
            Log.e("wmb", "--shutDown has an exception");
            e.printStackTrace();
        }
    }

关机shutdown代码,亲测有效。
注意点:
调用shutDown.invoke(IPowerManager, false,true);需要系统权限,在manifest中增加android:sharedUserId=”android.uid.system”,并将应用push到/system/priv-app目录下,重启才能生效。

  • 3
    点赞
  • 9
    收藏
    觉得还不错? 一键收藏
  • 2
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值