如何在Gradle中获取当前的构建类型

Naz*_*Jnr 11 android gradle android-studio build.gradle android-gradle-plugin

我的问题很直接,很容易理解。

在Gradle中,有什么方法可以在运行时获取当前的构建类型。例如,在运行汇编Debug任务时,build.gradle文件中的任务是否可以基于该任务与debug build变体相关的事实来做出决策?

样例代码

apply plugin: 'com.android.library'
ext.buildInProgress = "" 

buildscript {

repositories {
    maven {
        url = url_here
    }
}

dependencies {
    classpath 'com.android.tools.build:gradle:3.0.1'
}
}


configurations {
     //get current build in progress here e.g buildInProgress = this.getBuildType()
}

android {
     //Android build settings here
}

buildTypes {
         release {
          //release type details here
      }

       debug {
           //debug type details here
       }

    anotherBuildType{
          //another build type details here
    }

   }
}

dependencies {
      //dependency list here
}

repositories{
         maven(url=url2_here)
}


task myTask{
      if(buildInProgress=='release'){
           //do something this way
      }
      else if(buildInProgress=='debug'){
          //do something this way
      }
      else if(buildInProgress=='anotherBuildType'){
         //do it another way
     }
}
Run Code Online (Sandbox Code Playgroud)

综上所述

有没有办法让我的myTask {}中的构建类型准确进行?

Unl*_*uto 10

您可以通过解析以下内容来获取确切的构建类型applicationVariants

applicationVariants.all { variant ->
    buildType = variant.buildType.name // sets the current build type
}
Run Code Online (Sandbox Code Playgroud)

一个实现可能如下所示:

def buildType // Your variable

android {
    applicationVariants.all { variant ->
        buildType = variant.buildType.name // Sets the current build type
    }
}

task myTask{
    // Compare buildType here
}
Run Code Online (Sandbox Code Playgroud)

您也可以检查这个这个类似的答案。

更新资料

答案由这个问题帮助提问者解决问题。

  • 这个解决方案是一个魔术。您正在循环遍历所有构建变体,多次分配“buildType”,最后一次是/曾经是正确的当前构建类型。 (8认同)
  • 我已经尝试过这个,但它不起作用。当我在 myTask 中进行检查时,buildType 为 null (2认同)
  • 此外,它是一个库项目而不是一个应用程序,所以我使用了“libraryVariants.all”而不是“applicationVariants.all” (2认同)
  • 这不再有效。迭代的顺序与当前的构建类型无关。 (2认同)