当前位置:网站首页>Binder mechanism and Aidl communication example

Binder mechanism and Aidl communication example

2022-06-25 00:21:00 BY-91

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 .
     Insert picture description here

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();
}

 Insert picture description here

  • ③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)
    }
}
原网站

版权声明
本文为[BY-91]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/02/202202210550382550.html

随机推荐