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

时间:2018-05-04 16:11:32

标签: android android-studio gradle android-gradle build.gradle

我的问题非常直接且易于理解。

问题

在Gradle中,有什么办法可以在运行时获取当前的构建类型。例如,在运行汇编调试任务时,build.gradle文件中的任务是否可以根据此任务与调试版本变体相关的事实做出决策?

示例代码

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
     }
}

摘要

我有办法在 myTask {} 中准确了解正在构建的构建类型吗?

6 个答案:

答案 0 :(得分:6)

您可以通过解析applicationVariants

来获取确切的构建类型
applicationVariants.all { variant ->
    buildType = variant.buildType.name // sets the current build type
}

实施可能如下所示:

def buildType // Your variable

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

task myTask{
    // Compare buildType here
}

您也可以查看thisthis类似的答案。

<强>更新

<This通过this回答问题帮助提问者解决问题。

答案 1 :(得分:1)

这对我有用

applicationVariants.all { variant ->
    def variantType = variant.buildType.name
    println "Variant type: $variantType"
    if (variantType == "debug") {
       // do stuff
    }
}

答案 2 :(得分:0)

您可以通过以下代码snnipet直接检查版本

if (BuildConfig.FLAVOR.equals("paid")){
// do what you need to do for the paid version
} else {
// do what you need to do for the free version
}

您可以在this

阅读更多内容

答案 3 :(得分:0)

您应该getBuildConfigFields().get("MY_BUILD_TYPE").getValue())

https://stackoverflow.com/a/59994937/5279996

GL

答案 4 :(得分:0)

如果你想将构建类型名称作为版本名称的后缀(像我一样),只需将此行添加到版本名称:

debug {
    versionNameSuffix "-debug"
}

这样您就可以在构建名称中识别构建类型。它无需声明任何其他内容即可工作。

答案 5 :(得分:0)

在Android平台的Kotlin编程语言中获取当前正在使用的buildType的正确方法(Java的逻辑相同)

project.afterEvaluate {
   this.android().variants().all {

      this.assembleProvider.configure {

         this.doLast{
            val variant = this@all

            variant.outputs
                       .map
                       .forEach{
                           //do something with current buildType, or build flavor or whatever
                           println(variant.flavorName)
                           println(variant.buildType)
                       }
         }
      }
   }
}
相关问题