Binder机制:AIDL的使用

乘着准备面试的实现了一个简单的AIDLdemo 讲一下什么是 怎么做

新建一个工程demo 名字随便取 我的工程名叫 com.nicestars.aidldemo

然后新建一个IMyAidlInterface.aidl 文件

这一步会卡住 为什么呢 没找到新建类和文件的地方有aidl后缀可选

问了Ds和GPT之后发现 是这里有个选项

如图:

新项目点了这个选项之后会有提示 让我们再项目配置页面打开aidl支持 如下代码


    // 👇 添加这个配置项
    buildFeatures {
        aidl = true
    }

然后再次点击新建AIDL文件即可

文件如下 也就是写个接口

package com.nicestars.aidldemo;

// Declare any non-default types here with import statements

interface IMyAidlInterface {
    int add(int a, int b);
}

接下来再写一个Service

package com.nicestars.aidldemo

import android.app.Service
import android.content.Intent
import android.os.IBinder

class MyService : Service() {

    private val binder =object :IMyAidlInterface.Stub(){
        override fun add(a: Int, b: Int): Int {
           return a+b  //实现a+b
        }

    }

    override fun onBind(intent: Intent?): IBinder {
        return binder
    }
}

再mainfest文件里面绑定 这个MyService

<!-- 表示运行在独立子进程 -->
        <service
            android:name=".MyService"
            android:exported="true"
            android:process=":remote">
            <intent-filter>
                <action android:name="com.nicestars.aidldemo.MyService" />
            </intent-filter>
        </service>

最后在MainActivity里面使用这个Service

package com.nicestars.aidldemo

import android.content.ComponentName
import android.content.Intent
import android.content.ServiceConnection
import android.os.Bundle
import android.os.IBinder
import android.util.Log
import androidx.activity.enableEdgeToEdge
import androidx.appcompat.app.AppCompatActivity


class MainActivity : AppCompatActivity() {


    private var aidlInterface: IMyAidlInterface? = null

    private val connection = object : ServiceConnection {
        override fun onServiceConnected(name: ComponentName?, service: IBinder?) {
            aidlInterface = IMyAidlInterface.Stub.asInterface(service)
            val result = aidlInterface?.add(10, 20)
            Log.d("NiceStarsAIDL", "调用 add(10, 20) = $result")
        }

        override fun onServiceDisconnected(name: ComponentName?) {
            aidlInterface = null
        }
    }


    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        enableEdgeToEdge()
        setContentView(R.layout.activity_main)


        // 启动并绑定 Service
        val intent = Intent()
        intent.setClassName(this, "com.nicestars.aidldemo.MyService")
        bindService(intent, connection, BIND_AUTO_CREATE)


    }


    override fun onDestroy() {
        super.onDestroy()

        unbindService(connection)
    }
}

运行项目



2025-04-17 14:27:55.232  5039-5039  NiceStarsAIDL           com.nicestars.aidldemo               D  调用 add(10, 20) = 30


Binder机制:AIDL的使用
https://nicestars.net//archives/binderji-zhi-aidlde-shi-yong
作者
NiceStars
发布于
2025年04月17日
更新于
2025年04月17日
许可协议