Android ApiDemos example resolution (41): App-& gt; Service-& gt; Messeng

Source: Internet
Author: User

The preceding LocalService mainly provides components in the same Application. If you want to support different applications or processes, use the Service. You can use Messenger. Messgener can be used to support inter-process communication without AIDL.

The following steps describe how to use Messenger:

Define a Handler in the Service to process requests from the Client.
Use this Handler to create a Messenger (containing a reference to Handler ).
Messenger creates an IBinder object and returns it to the Client (onBind method ).
The Client uses the IBinder returned from the Service to reconstruct a Messenger object. This Messenger object can be used to send messages to the Service.
Service provides Handler to receive the Message from the Client. handleMessage is provided to process the Message.
In this way, the Service does not define a method that can be directly called by the Client. Instead, information is transmitted through "Message.

In this example, the Messenger Service involves two classes: MessengerServiceActivities and MessengerService.

First, let's take a look at the definition of the Service. In MessengerService, an IncomingHandler is defined to process messages from the Client.

[Java]
/**
* Handler of incoming messages from clients.
*/
Class IncomingHandler extends Handler {
@ Override
Public void handleMessage (Message msg ){
Switch (msg. what ){
Case MSG_REGISTER_CLIENT:
MClients. add (msg. replyTo );
Break;
Case MSG_UNREGISTER_CLIENT:
MClients. remove (msg. replyTo );
Break;
Case MSG_SET_VALUE:
MValue = msg. arg1;
For (int I = mClients. size ()-1; I> = 0; I --){
Try {
MClients. get (I). send (Message. obtain (null,
MSG_SET_VALUE, mValue, 0 ));
} Catch (RemoteException e ){
// The client is dead. Remove it from the list;
// We are going through the list from back to front
// So this is safe to do inside the loop.
MClients. remove (I );
}
}
Break;
Default:
Super. handleMessage (msg );
}
}
}
/**
* Handler of incoming messages from clients.
*/
Class IncomingHandler extends Handler {
@ Override
Public void handleMessage (Message msg ){
Switch (msg. what ){
Case MSG_REGISTER_CLIENT:
MClients. add (msg. replyTo );
Break;
Case MSG_UNREGISTER_CLIENT:
MClients. remove (msg. replyTo );
Break;
Case MSG_SET_VALUE:
MValue = msg. arg1;
For (int I = mClients. size ()-1; I> = 0; I --){
Try {
MClients. get (I). send (Message. obtain (null,
MSG_SET_VALUE, mValue, 0 ));
} Catch (RemoteException e ){
// The client is dead. Remove it from the list;
// We are going through the list from back to front
// So this is safe to do inside the loop.
MClients. remove (I );
}
}
Break;
Default:
Super. handleMessage (msg );
}
}
}
Then use this IncomingHandler to define a Messenger.

[Java]
Final Messenger mMessenger = new Messenger (new IncomingHandler ());
Final Messenger mMessenger = new Messenger (new IncomingHandler ());
It should be the "Bound" Service mode used in this method. onBind needs to return an IBind object, which can be passed through mMessenger. getBinder () returns the IBinder object associated with this Messenger. The Client can reconstruct a Messenger object through this IBinder object to establish a communication link with the Service.

[Java]
@ Override
Public IBinder onBind (Intent intent ){
Return mmesder. getBinder ();
}
@ Override
Public IBinder onBind (Intent intent ){
Return mmesder. getBinder ();
}
Let's look at the definition of the Client code MessengerServiceActivities in the onServiceConnected of ServiceConnection. This method returns the IBinder object defined by onBind of MessengerService:

[Java]
/** Messenger for communicating with service .*/
Messenger mService = null;

....
Public void onServiceConnected (ComponentName className,
IBinder service ){
// This is called when the connection with the service has been
// Established, giving us the service object we can use
// Interact with the service. We are communicating with our
// Service through an IDL interface, so get a client-side
// Representation of that from the raw service object.
MService = new Messenger (service );
MCallbackText. setText ("Attached .");

// We want to monitor the service for as long as we are
// Connected to it.
Try {
Message msg = Message. obtain (null,
MessengerService. MSG_REGISTER_CLIENT );
Msg. replyTo = mMessenger;
MService. send (msg );

// Give it some value as an example.
Msg = Message. obtain (null,
MessengerService. MSG_SET_VALUE, this. hashCode (), 0 );
MService. send (msg );
} Catch (RemoteException e ){
// In this case the service has crashed before we coshould even
// Do anything with it; we can count on soon being
// Disconnected (and then reconnected if it can be restarted)
// So there is no need to do anything here.
}
....
/** Messenger for communicating with service .*/
Messenger mService = null;
 
....
Public void onServiceConnected (ComponentName className,
IBinder service ){
// This is called when the connection with the service has been
// Established, giving us the service object we can use
// Interact with the service. We are communicating with our
// Service through an IDL interface, so get a client-side
// Representation of that from the raw service object.
MService = new Messenger (service );
MCallbackText. setText ("Attached .");
 
// We want to monitor the service for as long as we are
// Connected to it.
Try {
Message msg = Message. obtain (null,
MessengerService. MSG_REGISTER_CLIENT );
Msg. replyTo = mMessenger;
MService. send (msg );
 
// Give it some value as an example.
Msg = Message. obtain (null,
MessengerService. MSG_SET_VALUE, this. hashCode (), 0 );
MService. send (msg );
} Catch (RemoteException e ){
// In this case the service has crashed before we coshould even
// Do anything with it; we can count on soon being
// Disconnected (and then reconnected if it can be restarted)
// So there is no need to do anything here.
}
....
In this example, two-way communication between the Client and the Service is implemented. Therefore, the Client also defines a Messenger object mMessenger, which is used to process messages from the Service.

With the mService object, you can use send to send messages to the Service. If you need the Service to return information, you can define the message. replyTo object.

 
Author: mapdigit
 

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.