在用 Kotlin 编写的自定义插件中访问 gradle Android 插件

Access gradle Android plugin inside custom plugin written in Kotlin

我正在编写一个自定义 Gradle 插件,它应该能够从 Android 插件访问配置参数。

我当然可以通过 groovy 插件(这是我当前的代码)做到这一点:

MyPlugin.groovy:

class MyPlugin implements Plugin<Project> {
    void apply(Project project) {
        project.android.applicationVariants.all { variant ->
              variant.registerJavaGeneratingTask( // all the right parameters

我的问题是我不希望插件在 Groovy 中,我希望它使用 Kotlin。
在 Kotlin 中简单地输入 project.android 是行不通的,据我所知,我需要编写类似于以下内容的内容:

MyPlugin.kt

import com.android.build.gradle.AndroidBasePlugin

class MyPlugin : Plugin<Project> {
    override fun apply(target: Project) {
         val android = target.plugins.findPlugin(AndroidBasePlugin::class.java)
          // and call android here

我的主要问题是导入 import com.android. 不存在。
我尝试在 build.gradle.kts 上添加许多不同的依赖项,例如 implementation("com.android.tools.build:gradle:3.6.1"),但没有任何东西可以让我访问它。

问题:

  1. 这是正确的方法吗?

案例:
(yes) 2.如何导入和使用?
(否) 2. 正确的做法是什么?

tl;博士:

如何在 Gradle Kotlin 插件中编写 project.android.applicationVariants.all { variant ->

编辑:

@tim_yates 答案非常有效。谁有兴趣,这是最终代码。

build.gradle.kts:

plugins {
    `kotlin-dsl`
}

repositories {
    mavenCentral()
    jcenter()
    google()
}

dependencies {
    implementation("com.android.tools.build:gradle:3.6.1")
    ... my other dependencies
}

package-name/MyPlugin.kt:

import com.android.build.gradle.AppExtension
import com.android.build.gradle.api.ApplicationVariant
      (...)
  override fun apply(target: Project) {
    val android = target.extensions.findByType(AppExtension::class.java)
    android?.applicationVariants?.configureEach {
      configureVariant(target, this)
    }

  private fun configureVariant(...) { // register my taks there
}

你需要的是这样的东西:

        project.extensions.configure<AppExtension>("android") {
            it.applicationVariants.all {
                it.registerJavaGeneratingTask( // all the right parameters
            }
        }

而且您将需要 com.android.tools.build:gradle 依赖项。

为什么不被识别,我不确定...你在写一个独立的插件吗?如果是这样,你所拥有的作品......如果它是 buildSrc 文件夹中的内联插件,那么你需要将 lib 添加到 buildSrc build