AIDL 的学习日志
AIDL是什么(AI GENERATED)
AIDL(Android Interface Definition Language)是Android平台上的一种接口定义语言,用于定义不同进程之间通信的接口。它允许开发者在不同的应用程序或服务之间进行跨进程通信(IPC),使得它们能够共享数据和功能。AIDL通过定义接口文件(.aidl文件)来描述服务端提供的接口和客户端调用的方式。AIDL会自动生成相应的Java代码,开发者可以在服务端实现这些接口,并在客户端调用它们,从而实现跨进程通信。
attention
- AIDL 是同步接口, 没有超时机制
code generated
Java
会同时生成server和client的代码,server端的代码会有一个Stub类,client端的代码会有一个Proxy类。
server - Stub
- onTransact() 接收和分发客户端的跨进程请求
- 根据 code 判断要调用哪个方法。
- 解析参数(如 data.readInt())。
- 调用实际方法(如 this.getColor())。
- 写回结果(如 reply.writeInt(_result))。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49
@Override public boolean onTransact(int code, android.os.Parcel data, android.os.Parcel reply, int flags) throws android.os.RemoteException { java.lang.String descriptor = DESCRIPTOR; if (code >= android.os.IBinder.FIRST_CALL_TRANSACTION && code <= android.os.IBinder.LAST_CALL_TRANSACTION) { data.enforceInterface(descriptor); } if (code == INTERFACE_TRANSACTION) { reply.writeString(descriptor); return true; } switch (code) { case TRANSACTION_getRandomColor: { int _result = this.getRandomColor(); reply.writeNoException(); reply.writeInt(_result); break; } case TRANSACTION_getColor: { int _result = this.getColor(); reply.writeNoException(); reply.writeInt(_result); break; } case TRANSACTION_setColor: { int _arg0; _arg0 = data.readInt(); this.setColor(_arg0); reply.writeNoException(); break; } case TRANSACTION_getColorAsync: { com.example.aidlserver.IColorCallback _arg0; _arg0 = com.example.aidlserver.IColorCallback.Stub.asInterface(data.readStrongBinder()); this.getColorAsync(_arg0); reply.writeNoException(); break; } default: { return super.onTransact(code, data, reply, flags); } } return true; }
client - Proxy
- 远程调用方法实现
- 创建 Parcel 数据包。
- 写入接口名和参数。
- 调用 mRemote.transact() 发送请求。
- 读取服务端返回的数据。
- 回收 Parcel。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
@Override public int getRandomColor() throws android.os.RemoteException { android.os.Parcel _data = android.os.Parcel.obtain(); android.os.Parcel _reply = android.os.Parcel.obtain(); int _result; try { _data.writeInterfaceToken(DESCRIPTOR); boolean _status = mRemote.transact(Stub.TRANSACTION_getRandomColor, _data, _reply, 0); _reply.readException(); _result = _reply.readInt(); } finally { _reply.recycle(); _data.recycle(); } return _result; }