Three ways of using the Messenger binding Service
If you need to communicate in different process, you can use Messenger in Service to realize the process of communication.
If you use this way, you need to define a Handler object in Service (responsible for the response to the client to send over the Message).
The Messenger can be shared to the client of a IBinder object, client Message sent to Service through the IBinder object, and the aforementioned Handler object is the basis of all this.
Note: do not support multi thread communication using this way.
Let us have a look of communication using this way.！
Note: the Service must open to the outside world in a statement, android:exported= "true", and this paper is through the Intent startup Service, so in the Service statement can receive specific Action.
1,Create a Handler object in Service, sent from client to Message
2,Create a Messenger object based on the created Handler object
3,GetBinder using the Messenger method to obtain a IBinder object, and in the onBind method of the Service inverse.
4,Client in onServiceConnected to create a Messenger object based on the IBinder parameter (refer to the Messenger constructor)
5,Client can use a Messenger object to be sent to Service Message.
After five above we can make client communicate with Service. Client uses a Messenger object to send Service Message, Service Handler will respond to the message.
To achieve the above is only one-way communication, namely client Service to send a message, and if I need Service sends the message to client and how to do it?
In fact, this is also very easy to implement, let us then the above steps to achieve two-way communication.~
6,Create a Handler object in the client, for processing Service sent the message
7,Create a client Messenger object according to the client Handler object
8,We obtained the Service Messenger object in fifth steps, and through it to send messages to Service. At this time, we will replyTo field in a client Messenger object is assigned to the Message object to send
9,In the Service Handler Message will parse out client Messenger, and use the client Messenger object to send client messages
So we can achieve two-way communication of client and Service. Client and Service have their own Handler and Messenger objects, so that the other can give his message, notably client Messenger is passed to Service by Message replyTo.
The Demo link: http://pan.baidu.com/share/link?shareid=583593&uk=2953765628
Posted by Ernest at November 14, 2013 - 7:06 AM