When creating a service with binding capabilities, an ibinder object must be provided, which is used to provide a programming interface for the client to interact with the server. There are three methods to define this interface:
1. inherit the binder class
If your service is a private service of your application and runs in the same process as the client, you should create your interface by inheriting the binder class, in addition, Buddha returns an instance of this interface from the onbind () method. The client receives this binder object and can use this object to directly access the public methods implemented in the binder class or in the service.
This is the preferred technology when your service only works for your own applications in the background. The only reason for not using this method to create a service interface is that your service requires other applications or cross-process use.
2. Use messenger)
If your interface needs to work across different processes, you can use the messenger to create an interface for the service. In this way, the service defines the processor that responds to different message object types. This processor is the basis of a messenger. It can share an ibinder object with the client, allowing the client to send commands to the server using the message object. In addition, the client can define its own messenger so that the server can send messages to the client.
This is the easiest way to execute inter-process communication (IPC). Because all requests in the messenger queue are in a single thread, you do not need to design your service for thread security.
3. Use aidl (Android Interface Definition Language)
Aidl (Android Interface Definition Language) executes all the work of decomposing objects into primitives that can be understood by the operating system, and groups them into different processes that execute IPC (inter-process communication. The messenger technology is actually based on the aidl architecture. As mentioned above, the messenger creates a queue for all client requests in a single thread, so the service can only receive one request at a time. However, if you want the service to process multiple requests at the same time, you can directly use aidl. In this case, your service must be multi-threaded and thread-safe.
To use aidl directly, you must create a. aidl file that defines the programming interface. Android SDK uses this file to generate an interface defined in the implementation file and an abstract class for processing IPC, and then you can expand it in your service.
Note:Most applications should not use aidl to create binding services, because it may require multi-threaded capabilities and may lead to more complex implementations. Therefore, aidl is not applicable to most applications, and this document does not discuss how to use it to create services. If you are sure to use aidl directly, please refer to the aidl document.