Sunday, March 20, 2016

Android What is Remote Messenger Service


If you need to be able to write a Service that can perform complicated communication with clients in remote processes (beyond simply the use of Context.startService to send commands to it), then you can use the Messenger class instead of writing full AIDL files.

An example of a Service that uses Messenger as its client interface is shown here. First is the Service itself, publishing a Messenger to an internal Handler when bound:


On the activity side, we should keep a Messenger instance to communicate to the service. When creating a messenger, we can give an instance of Handler and that subclass can override the handleMessage function to handle the messages from the service. 

The other main component is ServiceConnection instance, which is the main interface to communicate with the service. The main two methods in this are, onServiceConnected and onServiceDisconnected. 

when onServiceConnected gets called back, it receives and IBinder object, this is tied with the second Messenger reference. In short, there are two Messenger Instances, one is representing the service connection from Service and the second one is Messenger for Service connection to send the messages to. 

References:

No comments:

Post a Comment