代码之家  ›  专栏  ›  技术社区  ›  Budius

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

  •  0
  • Budius  · 技术社区  · 6 年前

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

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

    我的问题是,我不希望插件在Groovy中,我希望它使用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. 不存在。
    implementation("com.android.tools.build:gradle:3.6.1") 但没有任何东西能让我接触到它。

    问题:

    1. 这是正确的方法吗?

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

    如何写作 project.android.applicationVariants.all { variant ->

    @蒂姆·耶茨的回答非常有效。对于感兴趣的人,这里是最终的代码。

    build.gradle.kts:

    plugins {
        `kotlin-dsl`
    }
    
    repositories {
        mavenCentral()
        jcenter()
        google()
    }
    
    dependencies {
        implementation("com.android.tools.build:gradle:3.6.1")
        ... my other dependencies
    }
    

    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
    }
    
    0 回复  |  直到 6 年前
        1
  •  2
  •   tim_yates    6 年前

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

    而且你需要 com.android.tools.build:gradle

    推荐文章