Wednesday, January 29, 2014

Android Binder, AIDL, Service, and API

Android Binder is an IPC mechanism used in Android. Binder can be accessed through the native code (C++) and also through Java code.

Here are some places where Binder are used:
1. When you use system service through mContext.getSystemService(...)
2. When you start another application through Intent.
3. When you're implementing a public service that uses AIDL file (this is pretty obvious)
4. When you're implementing interacting through different services using Messenger class

To me, what's the most interesting is that Android abstracts it so well such that I didn't realize I've been doing IPC calls so many times! In fact, I began my first Android programming without having any idea what an IPC was.

For the work I've been doing, I need to implement a piece of code that talks to the driver layer. Since I don't want to re-write the tedious JNI code multiple times (in case of it's needed somewhere else), I decided to create a public Service using AIDL convention. This service is the one that interacts with the native layer, and will then be exposed as an API in the SDK.
After that, it will essentially be wrapped one more time, such that user wouldn't have to actually interact with the service directly. Sounds like I'm over-complicating it, huh? Not really.. This is exactly how InputManager is working under the hood. When you do  mContext.getSystemService(INPUT_MANAGER), under the hood, InputManager class is interacting with InputManagerService. On the whole system, there's only a single instance of InputManagerService. This service is interacting with some native piece of codes that are tightly coupled to a lower layer. This way, as an application developer, we can all simply use the handy interface exposed through InputManager :)