Android--Messager and service

Source: Internet
Author: User

If you need your service and other processes to communicate, then you can use a Messenger to provide this interface.

This approach allows you to communicate IPC across processes without using AIDL.

implementation Steps

Here's a small summary of how to use Messenger:

1. The service implements a callback for each invocation of a Handler receive client.

2. Handler is used to create a Messenger object, which is a Handler reference.

3. Messenger creates a ibinder,service from Onbind () to return it to the client.

4. The client uses this ibinder to instantiate Messenger (a reference to the service's handler), which the client uses to send a message object to the service.

5. The service receives each message object in its handler, in its Handlemessage () method.

Code
 Public classMessengerserviceextendsservice{/**Command to the service to display a message*/    Static Final intMsg_say_hello = 1; /*** Handler of incoming messages from clients. */    classIncominghandlerextendsHandler {@Override Public voidhandlemessage (Message msg) {Switch(msg.what) { CaseMSG_SAY_HELLO:Toast.makeText (Getapplicationcontext (),"Hello!", Toast.length_short). Show ();  Break; default:                    Super. Handlemessage (msg); }        }    }    /*** Target We publish for clients to send messages to Incominghandler. */    FinalMessenger Mmessenger =NewMessenger (NewIncominghandler ()); /*** When binding to the service, we return a interface to our Messenger for * sending messages to the service. */@Override Publicibinder onbind (Intent Intent) {Toast.maketext (Getapplicationcontext (),"Binding", Toast.length_short). Show (); returnMmessenger.getbinder (); }}

Note the Handlemessage () method in handler is where the service receives the incoming message and decides what to do.

The only thing the client needs to do is create a Messenger based on the IBinder returned by the service, and send the message using the Send () method.

For example, here is a simple activity and service binding and sending information to the service:

 Public classActivitymessengerextendsactivity{/**Messenger for communicating with the service.*/Messenger Mservice=NULL; /**Flag indicating whether we have a called bind on the service.*/    BooleanMbound; /*** Class for interacting with the main interface of the service. */    PrivateServiceconnection mconnection =Newserviceconnection () { Public voidonserviceconnected (componentname className, IBinder service) {//This was called when the connection with the service had been//established, giving us the object we can use to//interact with the service. We is communicating with the//Service using a Messenger, so here we get a client-side//Representation of that from the raw IBinder object.Mservice =NewMessenger (service); Mbound=true; }         Public voidonservicedisconnected (componentname className) {//This was called when the connection with the service had been//unexpectedly disconnected--that's, its process crashed.Mservice =NULL; Mbound=false;    }    };  Public voidSayHello (View v) {if(!mbound)return; //Create and send a message to the service with using a supported ' what '//valueMessage msg =Message. Obtain (NULL, Messengerservice.msg_say_hello, 0, 0); Try{mservice.send (msg); }        Catch(RemoteException e) {e.printstacktrace (); }} @Overrideprotected voidonCreate (Bundle savedinstancestate) {Super. OnCreate (savedinstancestate);    Setcontentview (R.layout.main); } @Overrideprotected voidOnStart () {Super. OnStart (); //Bind to the serviceBindservice (NewIntent ( This, Messengerservice.class), mconnection, context.bind_auto_create); } @Overrideprotected voidOnStop () {Super. OnStop (); //Unbind from the service        if(mbound) {unbindservice (mconnection); Mbound=false; }    }}

  Note that this example does not show how the service responds to the client, and if you want the service to respond, you need to create a Messenger in the client.

Then when the client receives the onserviceconnected () callback method, it sends a message to the service, which contains the client Messenger in the ReplyTo parameter of its send () method.

I'm the dividing line of the king of the land Tiger.

Reference: Http://www.cnblogs.com/mengdd/tag/Android/default.html?page=4

Android--Messager and service

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.