Budius
Budius

Reputation: 39856

Access gradle Android plugin inside custom plugin written in Kotlin

I'm writing a custom Gradle plugin which should be able to access the configuration parameters from the Android plugin.

I can do certainly do this from a groovy plugin (which is my current code):

MyPlugin.groovy:

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

My problem is that I don't want the plugin to be in Groovy, I want it using Kotlin.
Simply typing project.android in Kotlin does not work, as far as I understand I would need to write something similar to what's below:

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

My main problem is that that import import com.android. does not exist.
I tried adding lots of different dependecies on build.gradle.kts, like example implementation("com.android.tools.build:gradle:3.6.1") but nothing gives me access to it.

questions:

  1. is that the right approach?

case:
(yes) 2. How do I import and use it?
(no) 2. What is the right approach?

tl;dr:

how to write project.android.applicationVariants.all { variant -> inside a Gradle Kotlin plugin

edit:

@tim_yates answer worked perfectly. To whom is interested, here is the final code.

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
}

Upvotes: 1

Views: 1905

Answers (1)

tim_yates
tim_yates

Reputation: 171194

What you'll need is something like this:

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

And you'll need the com.android.tools.build:gradle dependency as you say.

Why it's not being recognized, I'm not sure... Are you writing a standalone plugin? If so, what you have works... If it's an inline plugin in a buildSrc folder, then you'll need to add the lib to the buildSrc build

Upvotes: 3

Related Questions