当前位置:网站首页>Binder mechanism and Aidl communication example
Binder mechanism and Aidl communication example
2022-06-25 00:21:00 【BY-91】
List of articles
Introduce
- Binder It consists of four parts :Binder client 、Binder Server side 、Binder drive 、 Service registration query module .
- Binder A client is a process that wants to use a service .
- Binder The server is the process that actually provides services .
- Binder drive :
1. Client first through Binder Get a reference to an object in the server process ,
2. Through this reference , Directly call the method of the object to get the result .
3. When this reference object executes a method , It first passes the request of the client method call to Binder drive ;
4. then Binder The driver then sends the client request to the server process ;
5. After the server process receives the request , Call the server “ real ” Object to execute the called method ; After the results are obtained , Send the result to Binder drive ;
6.Binder The driver sends the result to our client ;
7. Final , We have the return value in the call of the client process .
8.Binder drive , It is equivalent to a role as a relay . With the help of this transit agent , We can call objects in other processes .
- Service Manager( Service registration query module )
1. When we call objects in other processes , First, get the object . This object actually represents what services another process can provide us ( More directly , Namely : Object that allows client processes to call ).
2. First, the server process needs to register in a certain place , Tell the system that I have an object that can be exposed to other processes to provide services . When the client process needs this service , Go to the registration place and find the object through query
Binder Workflow
- hypothesis : The client program Client Running in process A in , The server program Server Running in process B in .
- Because of the isolation of processes ,Client Can't read or write Server The content in , But the kernel can , and Binder The driver is running in kernel mode , therefore Binder The driver helps us transfer the request .
- With Binder drive ,Client and Server We can deal with each other , But in order to realize the single function , We are Client and Server Set up a proxy respectively :Client Agent for Proxy and Server Agent for Stub. such , By process A Medium Proxy And processes B Medium Stub adopt Binder Drive data exchange ,Server and Client Call directly Stub and Proxy The interface returns data .
- here ,Client Call directly Proxy This converges Binder Class , We can use a series of Manager To shield Binder Implementation details ,Client Call directly Manager To get data , The advantage of this is Client You don't need to know Binder How does it work .
- Client There are a variety of services you want , So how does it get Proxy or Manager What about ? The answer is through Service Manager Process to get .Service Manager Always the first service to start , After other server processes are started , Can be in Service Manager Register in , such Client You can go through Service Manager To get the service list of the server , Then select the server process method to be called .

AIDL Examples of Communications
- ① Two processes activity
<activity
android:name=".ServerActivity"
android:process=":remote" />
<activity android:name=".ClientActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
- ② establish aidl File and method for communication between client and server
/**
* @Author yangtianfu
* @Data 2021/4/1 18:01
* @Des ② establish aidl File and method for communication between client and server
*/
interface IMyAidlInterface {
void setName(String name);
String getName();
}

- ③AIDL The document states ,activity And other files cannot be called to IInfManager Interface , Need to be in app Of build.gradle In the document android{} Add
sourceSets{
main{
java.srcDirs = ['src/main/java', 'src/main/aidl']
}
}
- ④Service Created in Binder object ,onBind Method to return this object ,Binder Object IMyAidlInterface Methods in interfaces .Service Remember in AndroidManifest.xml Register in
<service
android:name=".MyService"
android:enabled="true"
android:exported="true"></service>
package com.example.binderapp
import android.app.Service
import android.content.Intent
import android.os.Binder
import android.os.IBinder
import android.os.RemoteException
/**
* @Author yangtianfu
* @Data 2021/4/1 18:09
* @Des ④Service Created in Binder object ,
* stay onBind Method to return this object ,Binder Object IMyAidlInterface Methods in interfaces .Service Remember in AndroidManifest.xml Register in
*/
class MyService : Service() {
private var name: String? = ""
override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int {
name = intent?.getStringExtra("name")
return super.onStartCommand(intent, flags, startId)
}
override fun onBind(intent: Intent): IBinder {
return binder
}
private val binder: Binder = object : IMyAidlInterface.Stub() {
@Throws(RemoteException::class)
override fun setName(mName: String) {
name = mName
}
@Throws(RemoteException::class)
override fun getName(): String {
return name?:""
}
}
}
- ⑤ Server side
package com.example.binderapp
import android.content.Intent
import android.os.Bundle
import android.view.View
import androidx.appcompat.app.AppCompatActivity
class ServerActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_server)
val intent = Intent([email protected],MyService::class.java)
intent.putExtra("name","BlissYang")
startService(intent)
}
fun jumpClient(view: View) {
startActivity(Intent([email protected], ClientActivity::class.java))
}
}
- ⑥ client
package com.example.binderapp
import android.content.ComponentName
import android.content.Context
import android.content.Intent
import android.content.ServiceConnection
import android.os.Bundle
import android.os.IBinder
import android.os.RemoteException
import android.util.Log
import androidx.appcompat.app.AppCompatActivity
class ClientActivity : AppCompatActivity() {
private var iMyAidlInterface: IMyAidlInterface? = null
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
val intent = Intent([email protected],MyService::class.java)
bindService(intent,connection, Context.BIND_AUTO_CREATE)
// Thread.sleep(3_000L)
// iMyAidlInterface?.name = " Client message "
}
private val connection: ServiceConnection = object : ServiceConnection {
override fun onServiceConnected(name: ComponentName, service: IBinder) {
iMyAidlInterface = IMyAidlInterface.Stub.asInterface(service)
try {
Log.i("ClientActivity", " Server data :" + iMyAidlInterface?.name)
iMyAidlInterface?.name = "YangTianfu"
Log.i("ClientActivity", "next:" + iMyAidlInterface?.name)
} catch (e: RemoteException) {
}
}
override fun onServiceDisconnected(name: ComponentName) {
}
}
override fun onDestroy() {
super.onDestroy()
unbindService(connection)
}
}
边栏推荐
- canvas螺旋样式的动画js特效
- Investment analysis and prospect forecast report of global and Chinese propargyl chloride industry from 2022 to 2028
- 【面试题】instancof和getClass()的区别
- Signal integrity (SI) power integrity (PI) learning notes (I) introduction to signal integrity analysis
- 有趣的checkbox计数器
- Human body transformation vs digital Avatar
- Go crawler framework -colly actual combat (II) -- Douban top250 crawling
- Eye gaze estimation using webcam
- 为什么越来越多的实体商铺用VR全景?优势有哪些?
- Difficult and miscellaneous problems: A Study on the phenomenon of text fuzziness caused by transform
猜你喜欢
![[interview question] what is a transaction? What are dirty reads, unrepeatable reads, phantom reads, and how to deal with several transaction isolation levels of MySQL](/img/95/02a58c9dc97bd8347b43247e38357d.png)
[interview question] what is a transaction? What are dirty reads, unrepeatable reads, phantom reads, and how to deal with several transaction isolation levels of MySQL

Creative SVG ring clock JS effect

5G dtu无线通信模块的电力应用

Meta&伯克利基于池化自注意力机制提出通用多尺度视觉Transformer,在ImageNet分类准确率达88.8%!开源...

为什么越来越多的实体商铺用VR全景?优势有哪些?
Microsoft won the title of "leader" in the magic quadrant of Gartner industrial Internet of things platform again!

C# Winform 最大化遮挡任务栏和全屏显示问题

JDBC —— 数据库连接

Ansible及playbook的相关操作

Zed acquisition
随机推荐
Basic summary of MySQL database knowledge
信号完整性(SI)电源完整性(PI)学习笔记(二十五)差分对与差分阻抗(五)
After 5 years of software testing in didi and ByteDance, it's too real
Investment analysis and prospect forecast report of global and Chinese triglycine sulfate industry from 2022 to 2028
Meta & Berkeley proposed a universal multi-scale visual transformer based on pooled self attention mechanism. The classification accuracy in Imagenet reached 88.8%! Open source
Scrollview height cannot fill full screen
Ansible及playbook的相关操作
Difficult and miscellaneous problems: A Study on the phenomenon of text fuzziness caused by transform
Paper review: U2 net, u-net composed of u-net
C program design topic 15-16 final exam exercise solutions (Part 1)
[figure database performance and scenario test sharp tool ldbc SNB] series I: introduction to data generator & Application to ges service
JPA learning 1 - overview, JPA, JPA core annotations, JPA core objects
Signal integrity (SI) power integrity (PI) learning notes (I) introduction to signal integrity analysis
∞符号线条动画canvasjs特效
On the difficulty of developing large im instant messaging system
C程序设计专题 18-19年期末考试习题解答(下)
Opengauss kernel: simple query execution
Analysis report on development mode and investment direction of sodium lauriminodipropionate in the world and China 2022 ~ 2028
Analysis report on operation mode and future development of global and Chinese methyl cyclopentanoate industry from 2022 to 2028
Outer screen and widescreen wasted? Harmonyos folding screen design specification teaches you to use it