Android Advanced Note 04:android Messenger of interprocess communication (different from Aidl)

Source: Internet
Author: User

I. Introduction to the messenger of communication between Android processes

(1) Introduction :

usually a talk between the process of communication, we will think of aidl, in fact, Messenger and Aidl function, can carry out inter-process communication. It is a message-based interprocess communication, just like a sub-thread and a UI thread sending a message, isn't it simple to write a aidl file, or is it a little cool? Ha ha. It also supports the recording of Messenger for client objects, and then enables one-to-many communication, and even as a forwarding point, any two processes can communicate through the server.

(2) Messenger Compare with Aidl :

When you need to perform IPC, it is easier to use Messenger for your interface than to use the AIDL implementation because Messenger queues all service calls and the pure Aidl interface sends multiple requests to the service at the same time. The service must then deal with multithreading.

For most applications, the service does not need to perform multithreading, so using Messenger allows the service to process one call at a time. If your service must perform multithreading, you should use Aidl to define the interface.

Second, The specific use of Messenger:

1. The client sends a message to the server (one-way communication)

Service side :

(1) Create a handler object and implement the Hanlemessage method for receiving messages from the client and processing them.

(2) Create a messenger (Messenger), package handler.

(3) Messenger creates a IBinder object that is returned to the client by Onbind

Client :

(1) Binding services in activity

(2) Create serviceconnection and use IBinder to instantiate Messenger

(3) using Messenger to send messages to the server

(4) Unbind service

(5) The server receives each Message in the Handlemessage () method

This way, the client does not invoke the "method" of the service. The message object, which is passed by the client, is received by the service in its Handler.

the above implementation is only one-way communication, that is, the client sends a message to the server .

2. Two-way communication between client and server

What if I need the server to send a message to the client?

In fact, this is also very easy to achieve, let us follow the above steps to achieve two-way communication:

(1) Create a handler object in the client that handles the messages sent by the service side.

(2) Create a client-side Messenger object and encapsulate the handler.

(3) assigns the client's Messenger object to the ReplyTo field of the message object to be sent.

(4) The client's messenger is parsed when the message is processed by handler on the server side, and the client Messenger object is used to send the message to the client.

This enables two-way communication between the client and the server.

Attention:

Note: The service must be open at the time of declaration, i.e. android:exported= "true"

is not looking dizzy, forget it, look directly below .

Three, code example:

(1) Server service:

1  Public classMyServiceextendsService {2     Private Static Final intCODE = 1;3      PublicMyService () {4     }5 @Override6      Publicibinder onbind (Intent Intent) {7         returnMmessenger.getbinder ();8     }9 Ten     //Create a messenger, package handler . One     PrivateMessenger Mmessenger =NewMessenger (NewHandler () { A @Override -          Public voidhandlemessage (Message msg) { -Message toclient =Message.obtain (); the             Switch(msg.what) { -                  CaseCODE: -                     //receive messages from the client and handle them -                     intarg =Msg.arg1; +Toast.maketext (Getapplicationcontext (), arg+ "", Toast.length_short). Show (); -TOCLIENT.ARG1 = 1111111111; +                     Try { A                         //replying to a client message at msg.replyTo.send (toclient); -}Catch(RemoteException e) { - e.printstacktrace (); -                     } -             } -             Super. Handlemessage (msg); in         } -     }); to}

(2) Client

1  PackageCom.zixue.god.fuck;2 3 ImportAndroid.content.ComponentName;4 Importandroid.content.Intent;5 Importandroid.content.ServiceConnection;6 ImportAndroid.os.Bundle;7 ImportAndroid.os.Handler;8 ImportAndroid.os.IBinder;9 ImportAndroid.os.Message;Ten ImportAndroid.os.Messenger; One Importandroid.os.RemoteException; A Importandroid.support.v7.app.AppCompatActivity; - ImportAndroid.util.Log; - ImportAndroid.view.View; the ImportAndroid.widget.Button; - ImportAndroid.widget.Toast; -  -  Public classMainactivityextendsappcompatactivity { +     Private BooleanMbond; -     PrivateMessenger Servermessenger; +     PrivateMyConn Conn; A  at @Override -     protected voidonCreate (Bundle savedinstancestate) { -         Super. OnCreate (savedinstancestate); - Setcontentview (r.layout.activity_main); -         //Binding Service -Intent Intent =NewIntent (); inIntent.setaction ("Com.zixue.god.myapplication.server"); -conn =Newmyconn (); to Bindservice (Intent, Conn, bind_auto_create); +Button Button =(Button) Findviewbyid (R.ID.BT); -Button.setonclicklistener (NewView.onclicklistener () { the @Override *              Public voidOnClick (View v) { $Message Clientmessage =Message.obtain ();Panax NotoginsengClientmessage.what = 1; -CLIENTMESSAGE.ARG1 = 12345; the                 Try { +Clientmessage.replyto =Mmessenger; A servermessenger.send (clientmessage); the}Catch(RemoteException e) { + e.printstacktrace (); -                 } $             } $         }); -     } -  the     Private classMyConnImplementsserviceconnection { - Wuyi @Override the          Public voidonserviceconnected (componentname name, IBinder service) { -             //Connection Successful WuServermessenger =NewMessenger (service); -LOG.I ("Main", "Service Connection succeeded"); AboutMbond =true; $         } -  - @Override -          Public voidonservicedisconnected (componentname name) { AServermessenger =NULL; +Mbond =false; the         } -     } $     PrivateMessenger Mmessenger =NewMessenger (NewHandler () { the @Override the          Public voidhandlemessage (Message msg) { theToast.maketext (Getapplicationcontext (), msg.arg1+ "", Toast.length_short). Show (); the             Super. Handlemessage (msg); -         } in     }); the @Override the     protected voidOnDestroy () { About         if(mbond) { the Unbindservice (conn); the         } the         Super. OnDestroy (); +     } -  the}

Android Advanced Note 04:android Messenger of interprocess communication (different from Aidl)

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.