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 class Messengerservice extends service{/** Command to the Service to display a message */static final int M    Sg_say_hello = 1;     /** * Handler of incoming messages from clients.            */class Incominghandler extends Handler {@Override public void Handlemessage (Message msg) { Switch (msg.what) {case MSG_SAY_HELLO:Toast.makeText (Getapplicati                    Oncontext (), "hello!", Toast.length_short). Show ();                Break            Default:super.handleMessage (msg);     }}}/** * Target We publish for clients to send messages to Incominghandler.    */FINAL Messenger Mmessenger = new Messenger (new Incominghandler ());     /** * When binding to the service, we return a interface to our Messenger for * sending messages to the service. */@Override public ibinder onbind (Intent Intent) {toAst.maketext (Getapplicationcontext (), "binding", Toast.length_short). Show ();    return Mmessenger.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 class Activitymessenger extends activity{/** Messenger for communicating with the service. */Messenger Mser    vice = null; /** Flag indicating whether we have a called bind on the service.    */Boolean Mbound;     /** * Class for interacting with the main interface of the service. */private Serviceconnection mconnection = new Serviceconnection () {public void onserviceconnected (Component            Name ClassName, IBinder service) {//This was called when the connection and the service has 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//Represen            Tation of that from the raw IBinder object.            Mservice = new Messenger (service);        Mbound = true; } public void onservicedisconnected (ComponentName className) {//This is called when The connection with the service have been//unexpectedly disconnected--that's, its process crashed.            Mservice = null;        Mbound = false;    }    };        public void SayHello (View v) {if (!mbound) return;                Create and send a message to the service, using a supported ' what '//value message MSG = message        . Obtain (null, Messengerservice.msg_say_hello, 0, 0);        try {mservice.send (msg);        } catch (RemoteException e) {e.printstacktrace ();        }} @Override protected void OnCreate (Bundle savedinstancestate) {super.oncreate (savedinstancestate);    Setcontentview (R.layout.main);        } @Override protected void OnStart () {Super.onstart (); Bind to the service Bindservice (new Intent (this, messengerservice.class), Mconnection, Context.bi    Nd_auto_create); } @Override Protected void OnStop () {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.

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.