Detailed explanation of messenger principle and basic usage in Android

This blog mainly records the basic principle and usage of messenger in Android.

In short, Messenger is actually the wrapper of binder communication. It is an interprocess communication tool based on message passing.

Usually, we can create a messenger in process a and then pass it to process B. Then, process B can communicate with process a through messenger.

Messenger is usually used with handler. Let's look at the corresponding source code:

Follow up the getimessenger function of handler:

As can be seen from the above code, Messenger actually acts as a wrapper for binder server.

When we create messenger in process a and deliver it to process B, Messenger needs to perform the operations defined by the Parcelable interface, so:

Follow up on another constructor for messenger:

Therefore, when messenger is passed from process a to process B, it becomes the wrapper of binder communication client.

When using the messenger interface in process B:

The above is the principle of messenger communication. Now let's actually test it. We define a simple demo, including an activity and a service, where service and activity are in different processes.

The definitions in androidmanifest.xml are as follows:

The interface of activity is very simple. When clicked, it will send a message like service. The activity code is as follows:

The code corresponding to service is as follows:

The code for obtaining the process name is as follows:

The above codes are relatively simple. Now let's look at the running results:

02-20 21:25:15.760 D/ZJTest (30460): Activity,pid: 30460,name: stark.a.is.zhang.messengertest 02-20 21:25:15.769 D/ZJTest (30428): Service,pid: 30428,name: .remote 02-20 21:25:32.111 D/ZJTest (30428): receive msg: 1

It can be seen from the log that activity and servie run in different processes, and messenger can indeed deliver messages between different processes.

The above is the whole content of this article. I hope it will be helpful to your study, and I hope you can support programming tips.

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>