文章目录
AIDL的原理
可以利用ALDL定义客户端与服务均认可的编程接口,以便二者使用进程间通信 (IPC) 进行相互通信。在 Android 中,一个进程通常无法访问另一个进程的内存。因此,为进行通信,进程需将其对象分解成可供操作系统理解的原语,并将其编组为可供您操作的对象。编写执行该编组操作的代码较为繁琐,因此 Android 会使用 AIDL 为您处理此问题。
AIDL 可以理解成是一个范式, 通过这个范式编写接口文件, 然后利用Android的AIDL工具 会生成继承binder所需要能力的头文件。
构建AIDL的流程
以automotive的audiocontrol模块为例
- 编写AIDL接口文件,编写Android.bp, 通过AIDL 生成头文件
其aidl的文件位于下面的目录
hardware/interfaces/automotive/audiocontrol/aidl/android/hardware/automotive/audiocontrol/
编译会在下面的目录生成实现binder通信的接口文件。
接口文件有java cpp ndk三种类型。 使得能够被不同的客户端和服务端的代码引用到。
out/soong/.intermediates/hardware/interfaces/automotive/audiocontrol/aidl/android.hardware.automotive.audiocontrol-V2-cpp-source/gen/include/android/hardware/automotive/audiocontrol$ ls
AudioFocusChange.h BnFocusListener.h BpDuckingInfo.h IAudioControl.h
BnAudioControl.h BnMutingInfo.h BpFocusListener.h IFocusListener.h
BnAudioFocusChange.h BpAudioControl.h BpMutingInfo.h MutingInfo.h
BnDuckingInfo.h BpAudioFocusChange.h DuckingInfo.h
- 实现service,实现service对应的bin,以及rc,注册服务到servicemananger
AudioContro 实现的demo bin位于hardware/interfaces/automotive/audiocontrol/aidl/default
目录下,编译会生成
android.hardware.automotive.audiocontrol-service.example这样的bin 这个bin在 audiocontrol-default.rc 中启动。
当然服务端的是 就是把audiocontrol的服务注册到servicemanger中。
std::shared_ptr<AudioControl> audioControl = ::ndk::SharedRefBase::make<AudioControl>();
const std::string instance = std::string() + AudioControl::descriptor + "/default";
binder_status_t status =
AServiceManager_addService(audioControl->asBinder().get(), instance.c_str());
CHECK_EQ(status, STATUS_OK);
服务的名字在audiocontrol-default.xml中定义为
android.hardware.automotive.audiocontrol.IAu