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 similar goal.
In Java word, there are similar classes, as shown in diagram below.
|Class Diagram for Binder/Interface in Android Java Layer|
Java AIDL GeneratorLuckily, 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 GeneratorGood 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.
For a comprehensive introduction of how to use C++ AIDL, read this. Many Android system components has already switched from hand crafted interface writing to use C++ AIDL. Probably, you want too.