[Zhaohuaxishi] inter-process communication, you know AIDL, on the [OUT] Zhaohuaxishi Android Performance chapter of the (seven) Android cross-process communication papers

I. Introduction

      Lift the cross-process communication, most people would first think AIDL. We know that with AIDL to achieve inter-process communication, you need the client and server are added on aidl file, and to achieve aidl corresponding interface on the server side of the Service. If you need the server to the client send a message, still need to add a callback aidl file related, and the use of RemoteCallbackList to assist in achieving this function. In my other article [Android] Zhaohuaxishi Performance chapter of the (seven) Android cross-process communication papers in it had AIDL devoted to implementation of the client and server communicate with each other, you can see clear introduction of this article. This article will explain the other in a more simple way --Messenger, to achieve the client and server inter-process communication with each other.

 

Two, Messenger Introduction

       Messenger translated into messenger, by definition, is used to transfer information, you can pass Message objects in different processes through it. We need to put the information passed in the Message, and then passed through Messenger Message to each other, you can easily achieve inter-process data transfer. In fact Messenger is a lightweight IPC (inter-process communication) mode, it is still the underlying implementation AIDL. It is a message-based interprocess communication, like a child thread and UI thread sends a message that, Demo in the server and client use Handler, just illustrates this point.

 

Third, sample code demonstrates

       Further ado, here we take a look at a complete Demo, to feel intuitive to use Messenger. Demo demo of this function is very simple, the client sends a message to the server, the server receives the message and then sends a message to the client as a response.

  1, the server code implementation

 1 public class MessengerService extends Service {
 2     private static final String TAG = "Messenger-Demo";
 3     private static final int MSG_CLIENT = 0x001;
 4     private static final int MSG_SERVER = 0X002;
 5     private static final String KEY_CLIENT = "key_client";
 6     private static final String KEY_SERVER = "key_server";
 7 
 8     private final Messenger mMessenger = new Messenger(new MessageHandler());
 9 
10     @Nullable
11     @Override
12     public IBinder onBind(Intent intent) {
13         return mMessenger.getBinder();
14     }
15 
16     private static class MessageHandler extends Handler {
17         @Override
18         public void handleMessage(Message msg) {
19             switch (msg.what) {
20                 case MSG_CLIENT:
21                     Log.d(TAG, "receive msg from Client:" + msg.getData().getString(KEY_CLIENT));
22                     Messenger messenger = msg.replyTo;
23                     Message serverMsg = Message.obtain();
24                     serverMsg.what = MSG_SERVER;
25                     Bundle bundle = new Bundle();
26                     bundle.putString(KEY_SERVER, "Hello Client! I am fine, thank you");
27                     serverMsg.setData(bundle);
28                     try {
29                         messenger.send(serverMsg);
30                     } catch (RemoteException e) {
31                         e.printStackTrace();
32                     }
33                     break;
34                 default:
35                     super.handleMessage(msg);
36             }
37         }
38     }
39 }
View Code

       Registration correspond to the manifest file

1 <service
2     android:name=".MessengerService "
3     android:exported="true"/>

It should be noted that the third line, the need to provide Service call other applications, the need to set the attribute value to true.

  2, client code implemented

 1 public class MessengerClientActivity extends AppCompatActivity {
 2 
 3     private static final String TAG = "Messenger-Demo";
 4     private static final int MSG_CLIENT = 0x001;
 5     private static final int MSG_SERVER = 0X002;
 6     private static final String KEY_CLIENT = "key_client";
 7     private static final String KEY_SERVER = "key_server";
 8     private static final String SERVER_PKGNAME = "com.example.messageserver";
 9     private static final String SERVICE_PATH = "com.example.messageserver.MessengerService";
10     private Messenger mRemoteMessenger;
11     private Messenger mLocalMessenger = new Messenger(new MessengerClientHandler());
12 
13     @Override
14     protected void onCreate(Bundle savedInstanceState) {
15         super.onCreate(savedInstanceState);
16         setContentView(R.layout.activity_main);
17         Log.d(TAG,"onCreate");
18         bindService();
19     }
20 
21     private void bindService() {
22         Intent intent = new Intent();
23         ComponentName componentName = new ComponentName(SERVER_PKGNAME, SERVICE_PATH);
24         intent.setComponent(componentName);
25         bindService(intent, mServiceConnection, Context.BIND_AUTO_CREATE);
26     }
27 
28     private static class MessengerClientHandler extends Handler {
29         @Override
30         public void handleMessage(Message msg) {
31             switch (msg.what) {
32                 case MSG_SERVER:
33                     Log.d(TAG, "receive msg from Server:" + msg.getData().getString(KEY_SERVER));
34                     break;
35                 default:
36                     break;
37             }
38             super.handleMessage(msg);
39         }
40     }
41 
42     private ServiceConnection mServiceConnection = new ServiceConnection() {
43         @Override
44         public void onServiceConnected(ComponentName name, IBinder service) {
45             mRemoteMessenger = new Messenger(service);
46             Message clientMsg = Message.obtain();
47             clientMsg.what = MSG_CLIENT;
48             Bundle bundle = new Bundle();
49             bundle.putString(KEY_CLIENT, "Hello,Server! How are you ?");
50             clientMsg.setData(bundle);
51             clientMsg.replyTo = mLocalMessenger;
52             try {
53                 mRemoteMessenger.send(clientMsg);
54             } catch (RemoteException e) {
55                 e.printStackTrace();
56             }
57         }
58 
59         @Override
60         public void onServiceDisconnected(ComponentName name) {
61 
62         }
63     };
64 
65     @Override
66     protected void onDestroy() {
67         super.onDestroy();
68         unbindService(mServiceConnection);
69     }
70 }
View Code

  3, run

       First start running the server, and then start the client, you can see the following log information:

1 15185-15185/com.example.messageserver D/Messenger-Demo: receive msg from Client:Hello,Server! How are you ?
2 14269-14269/com.example.messageclient D/Messenger-Demo: receive msg from Server:Hello Client! I am fine, thank you

 So that the client and server to complete a communicate with each other. From the point of view of code, you can feel, compared to the direct use AIDL way, Messenger simple and convenient for a lot.

 

Four, Messenger of using the steps

       Through previous Demo intuitive feel of using Messenger, the interaction process is generally about six steps:

 

 

       Demo and control on the map, should be able to easily understand the flow of the interaction of the Messenger. It should be noted that, Messenger is actually sending a message to the Server side Handler, it is a combination of IBinder instance returned from the server to generate server-side remote agent; to the client Handler sends a message of Messenger also step 4 is sent to the server side client local Messenger, can be understood as his Messenger to their Handler in sending a message.

 

V. Contact with the distinction of Messenger and AIDL

       We said earlier Messager or underlying implementation AIDL, it is their contact. The difference between them:

    (1) Messenger is simple to use than AIDL convenient.

    (2) AIDL client interface can simultaneously send multiple requests to the server, the server applications that require multi-threaded processing. The Messenger will all requests queued (Handler corresponding MessageQueue), so that a server processing a call, do not handle multi-threading issues. In most cases, the server does not need to perform multi-threaded processing Messenger at this time choose a more suitable way, and if the client's request requires the server to perform multi-threaded processing, should be used to achieve AIDL, choose, or according to the actual needs situation to choose.

 

Epilogue

       As the author is limited, if the article is described inaccurate or inappropriate place, please let us know readers, thank you very much!

Guess you like

Origin www.cnblogs.com/andy-songwei/p/11774836.html