Messenger between Android processes and communication between android Processes

Source: Internet
Author: User

Messenger between Android processes and communication between android Processes

I 've been reading binder over the past two days. I 've accidentally seen something like messenger in the document. I think it's quite interesting. I 'd like to share it with you.

When we talk about inter-process communication, we will think of AIDL. In fact, both messenger and AIDL can communicate between processes. It is message-based communication between processes, just like sending messages through sub-threads and UI threads. Isn't it easy to write AIDL files. Haha.

In addition, it also supports recording the Messenger of the client object, and can implement one-to-many communication. Even as a transfer place, any two processes can communicate through the server.

Compared with AIDL:

When you need to execute IPC, it is easier to use Messenger for your interface than to use AIDL, because Messenger will queue all service calls, the pure AIDL interface will send multiple requests to the service at the same time, and the service must deal with multithreading later.

For most applications, the Service does not need to perform multi-threaded processing. Therefore, using Messenger allows the service to process one call at a time. If your service must be multi-threaded, you should use AIDL to define the interface.

Next, let's take a look at how to write:

Server:

1. Create a handler object and implement the hanlemessage method to receive and process messages from the client.

2. Create a messenger and encapsulate handler

3. Create an IBinder object in messenger and return it to the client through onBind.

Client:

1. Bind a service to the activity

2. Create ServiceConnection and use IBinder to instantiate Messenger

3. Use Messenger to send messages to the server

4. Unbind a service

5. The server receives each Message in the handleMessage () method.

In this way, the client does not call the "method" of the service ". The "Message object" transmitted by the client is received by the Service in its Handler.

The above only implements one-way communication, that is, the client sends messages to the server. What should I do if I need the service end to send messages to the client?

In fact, this is also very easy to implement. Let's proceed with the above steps to implement two-way communication.

1. Create a Handler object in the client to process messages sent from the server.

2. Create a client's own messenger object and encapsulate handler.

3. Assign the Messenger object of the client to the replyTo field of the Message object to be sent.

4. parse the client's Messenger when the server's Handler processes the Message, and use the client's Messenger object to send the Message to the client.

In this way, two-way communication between the client and the server is realized.

Note: The Service must be open to the outside when it is declared, that is, android: exported = "true"

Are you dizzy? Forget it. Just look at the following.

Let's look at a simple example.

1 package com. zixue. god. myapplication; 2 3 import android. app. service; 4 import android. content. intent; 5 import android. OS. handler; 6 import android. OS. IBinder; 7 import android. OS. message; 8 import android. OS. messenger; 9 import android. OS. remoteException; 10 import android. widget. toast; 11 12 // service13 public class MyService extends Service {14 private static final int CODE = 1; 15 public MyService () {16} 17 @ Override18 public IBinder onBind (Intent intent) {19 return mMessenger. getBinder (); 20} 21 22 // create a courier and encapsulate handler23 private Messenger mMessenger = new Messenger (new Handler () {24 @ Override25 public void handleMessage (Message msg) {26 Message toClient = Message. obtain (); 27 switch (msg. what) {28 case CODE: 29 // receives messages from the client and processes 30 int arg = msg. arg1; 31 Toast. makeText (getApplicationContext (), arg + "", Toast. LENGTH_SHORT ). show (); 32 toClient. arg1 = 1111111111; 33 try {34 // reply to client message 35 msg. replyTo. send (toClient); 36} catch (RemoteException e) {37 e. printStackTrace (); 38} 39} 40 super. handleMessage (msg); 41} 42}); 43}

// Client

1 package com. zixue. god. fuck; 2 3 import android. content. componentName; 4 import android. content. intent; 5 import android. content. serviceConnection; 6 import android. OS. bundle; 7 import android. OS. handler; 8 import android. OS. IBinder; 9 import android. OS. message; 10 import android. OS. messenger; 11 import android. OS. remoteException; 12 import android. support. v7.app. appCompatActivity; 13 import android. util. log; 14 import android. view. view; 15 import android. widget. button; 16 import android. widget. toast; 17 18 public class MainActivity extends AppCompatActivity {19 private boolean mBond; 20 private Messenger serverMessenger; 21 private MyConn conn; 22 23 @ Override24 protected void onCreate (Bundle savedInstanceState) {25 super. onCreate (savedInstanceState); 26 setContentView (R. layout. activity_main); 27 // bind Service 28 Intent intent = new Intent (); 29 intent. setAction ("com. zixue. god. myapplication. server "); 30 conn = new MyConn (); 31 bindService (intent, conn, BIND_AUTO_CREATE); 32 Button button = (Button) findViewById (R. id. bt); 33 button. setOnClickListener (new View. onClickListener () {34 @ Override35 public void onClick (View v) {36 Message clientMessage = Message. obtain (); 37 clientMessage. what = 1; 38 clientMessage. arg1 = 12345; 39 try {40 clientMessage. replyTo = mMessenger; 41 serverMessenger. send (clientMessage); 42} catch (RemoteException e) {43 e. printStackTrace (); 44} 45} 46}); 47} 48 49 private class MyConn implements ServiceConnection {50 51 @ Override52 public void onServiceConnected (ComponentName, IBinder service) {53 // connection successful 54 serverMessenger = new Messenger (service); 55 Log. I ("Main", "service connection succeeded"); 56 mBond = true; 57} 58 59 @ Override60 public void onServiceDisconnected (ComponentName name) {61 serverMessenger = null; 62 mBond = false; 63} 64} 65 private Messenger mMessenger = new Messenger (new Handler () {66 @ Override67 public void handleMessage (Message msg) {68 Toast. makeText (getApplicationContext (), msg. arg1 + "", Toast. LENGTH_SHORT ). show (); 69 super. handleMessage (msg); 70} 71}); 72 @ Override73 protected void onDestroy () {74 if (mBond) {75 unbindService (conn); 76} 77 super. onDestroy (); 78} 79 80}

In this way, two-way communication between the client and the server is realized, isn't it easy.

 

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.