Android 使用反射调用自定义AIDL **.Stub.asInterface(IBinder obj)、反

自定义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目录下,重启才能生效。