Android AIDL - 生成标头+本机代码的实现(android NDK)

问题描述 投票:0回答:1

有没有办法让 gradle 为本机代码(android NDK)生成 AIDL 文件的标头和实现?我按照此处的说明进行操作(https://developer.android.com/guide/components/aidl),但这只会生成 java/kotlin 代码的代码。它不会为本机代码 (c++) 生成任何内容。

我能够使用此处描述的“aidl”工具手动生成标头+实现(https://source.android.com/devices/architecture/aidl/aidl-backends),但我希望有一个通过 gradle 来完成此操作的方法,以便为我解决这个问题。

谢谢!

android android-ndk aidl
1个回答
0
投票

正如 @Mykola 在评论中提到的,我们可以有一个预构建 Gradle 任务。

Android Gradle 模块(项目)的文件结构:

├── src
│   ├── main
│   │   ├── aidl
│   │   │   ├── com
│   │   │   │   ├── example
│   │   │   │   │   ├── IMyService.aidl
├── build.gradle.kts

IMyService.aidl

package com.example;
interface IMyService {
    // Function declarations of the interface come here...
}

build.gradle.kts

plugins {
    alias(libs.plugins.androidApplication)
}

android {
    compileSdk = 34
    defaultConfig {
        minSdk = 29
        targetSdk = 34
    }
}

tasks.create("compileAidlNdk") {
    doLast {
        // Path to aidl tool
        val aidl = arrayOf<String>(
            project.android.sdkDirectory.absolutePath,
            "build-tools", project.android.buildToolsVersion, "aidl"
        ).joinToString(File.separator)

        val outDir = arrayOf<String>(
            project.projectDir.absolutePath, "src", "main", "cpp", "aidl"
        ).joinToString(File.separator)

        val headerOutDir = arrayOf<String>(
            project.projectDir.absolutePath, "src", "main", "cpp", "includes"
        ).joinToString(File.separator)

        val searchPathForImports = arrayOf<String>(
            project.projectDir.absolutePath, "src", "main", "aidl"
        ).joinToString(File.separator)

        val aidlFile = arrayOf<String>(
            project.projectDir.absolutePath, "src", "main", "aidl",
            "com", "example", "IMyService.aidl"
        ).joinToString(File.separator)

        // Exec aidl command to generate headers and source files for IMyService.aidl
        ProcessBuilder(aidl,
            "--lang=ndk",
            "-o", outDir,
            "-h", headerOutDir,
            "-I", searchPathForImports,
            aidlFile
        ).start().waitFor()
    }
}

// To generate headers and source files for IMyService.aidl before each build
afterEvaluate {
    tasks.named("preBuild") {
        dependsOn(tasks.named("compileAidlNdk"))
    }
}
© www.soinside.com 2019 - 2024. All rights reserved.