For convenience of description, the following "server" represents the service, with the "client" representing one end of the service. There are many ways to communicate with a service, such as:.
- Directly starts the service, passing in the parameters via intent.
- Binding service also has three different implementations for different scenarios, using binder binding service for direct communication
* implementation of a : If the service is only used in its own program, and in the same process, then you can extend the Binder class in the service and provide the relevant interface, so that when the client first and the server binding timing, The server can get our extended Binder class to the client via Onbind. A more common practice is to write a method in the extended Binder class to get the current service instance, so that the client binding service gets the binder to get the service instance to access the service's public methods, fields, and so on. Achieve the purpose of communication.
* Implementation Two : However, if the service is intended to be used by other processes of the program or to be used by other programs, it cannot be implemented because the implementation of one is in-process communication, not interprocess communication. If you want to communicate between the processes, to carry out a more complex process, so Android provides us with Messenger, let us more simple and quick to achieve inter-process communication. The role of Messenger, as the name implies, the Messenger, send what letter? It's message! in handler. We can create a handler between the server and the client, processing the message from each other separately to achieve the purpose of communication. At the time of the service binding, the client can get Messenger from the server, and through this messenger, the client can send a message to the server, and because of this messenger, we can create our own messenger on the client, Messenger sent to the server through the service side, so that the server can also send a message to the client through this messenger, so that the communication between the two sides. Based on this implementation messenger will put all the requests into a separate process queue, so you do not have to design the service as a thread-safe mode, which is applicable and useful in most scenarios. However, this implementation does not apply if the service side needs to be processed concurrently.
* Implementation Three : implementation of process communication based on AIDL, the implementation of this approach is that Android in your own process internally maintain a thread pool, the allocation of remote process calls in the thread pools processing, so the implementation of the Aidl interface must be self-assured threads security. The specific implementation of reference to Google's documentation.
A simple summary of communication with service