Android AIDL deep dive

In "Yet Another Deep Dive of Android Binder Framework", we introduced the native Binder/Interface class hierarchy and explained how to use those classes to create a service that supports IPC. In this post, we will switch from native world to the Java word, explaining how to achieve the similar goal. 


In Java world, there are similar classes,  as shown in the diagram below.

Class Diagram for Binder/Interface in Android Java Layer

Java AIDL Generator 

Luckily, Java application developer don't really need to deal with the Binder class directly. Instead, they use the AIDL tool to generate the code that will take care of the IPC stuff.  There are lots of excellent tutorials out there explaining how to define the interface using AIDL syntax and generate the proxy/stub code automatically and base on that implement your own service.  You can start with this official doc

Here, what I want to show you is what is actually generated and how it is related with the structure
we have shown in the native layer.  As shown in above diagram, the AIDL tool actually generated interface class definition, the proxy and stub code. Compared with the digram in native layer, the ICoolService.stub.proxy is equivalent to BpInterface, and the ICoolService.stub is equivalent to BnInterface.  So, the benefit is don't need to code those tedious marshaling and marshaling code in the step 2 and 3 as shown here. That enable you focus on implementing your your business logic.  Life is much easier!

C++ AIDL Generator

Good news is, recently, we can also generate similar stuff for the native code using cpp-aidl.
Actually, You can generate both the Java and c++ helper classes from single .aidl file, which is a great way to keep things in sync if , say, you have a native service and want to expose it to Java client.

Parcelable

For primitive types, such as string and int, aidl generator knows how to pack and unpack it and send it through the IPC channel. But for composite or user-defined type, aidl generator don't know how to do it and will need your assistance.  That is what Parcelable for.  When pack it, aidl generator will call writeToParcel. When unpack it, aidl generator will call readFromParcel.  It is your responsibility to implement those two methods correctly. The exactly syntax or convention varies a little bit between C++ and Java but the theory is exactly the same. Actually, you can pack it from C++ and unpack it in the Java side, or vise versa.

For a comprehensive introduction of how to use C++ AIDL, read this. Many Android system components has already switched from handcrafted interface writing to use C++ AIDL. Probably, you want too.