29

My Question is very direct and easy to understand.

Question

In Gradle, is there any way I can get the current build type at runtime. For example, when running an assembleDebug task, can tasks within the build.gradle file make decisions based on the fact that this task is related to the debug build variant?

Sample Code

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

In Summary

Is there a way for me to get exactly the build type in progress within myTask{}?

Naz_Jnr
  • 570
  • 1
  • 7
  • 17
  • did you find a solution? I'm trying to solve the next task https://stackoverflow.com/questions/52677223/how-to-check-if-current-build-is-debug-or-release-in-build-gradle – user924 Oct 06 '18 at 09:50

10 Answers10

21

You can get the exact build type by parsing your applicationVariants:

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

A implementation could look like the following:

def buildType // Your variable

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

task myTask{
    // Compare buildType here
}

Also you can check this and this similar answers.

Update

This answer by this question helped the questioner to settle the problem.

UnlikePluto
  • 3,101
  • 4
  • 23
  • 33
  • 4
    I have tried this out, but it doesn't work. buildType is null when I make the checks inside myTask – Naz_Jnr May 07 '18 at 07:35
  • 3
    Also, it is a library project and not an application so I used 'libraryVariants.all' and not 'applicationVariants.all' – Naz_Jnr May 07 '18 at 07:37
  • Thanks. This has saved me some stress. Been trying different methods to work around it in the last few days withouth success, not knowing its a Gradle limitation. – Naz_Jnr May 07 '18 at 07:57
  • I'm going to update my answer later accordingly to match your question – UnlikePluto May 07 '18 at 08:15
  • and what `buildType` is supposed to have? String? I tried `if (buildType == "debug")` but it returns `false`... I'm trying to solve the next task https://stackoverflow.com/questions/52677223/how-to-check-if-current-build-is-debug-or-release-in-build-gradle – user924 Oct 06 '18 at 09:48
  • and it's `null`: `Cannot invoke method contains() on null object` – user924 Oct 06 '18 at 09:49
  • so `buildType` is `null` – user924 Oct 06 '18 at 09:49
  • 21
    This solution is a magic trick. You're looping over _all_ build variants, assigning `buildType` multiple times, and last is/was by some coincidence correct current build type. – Peter Dec 13 '19 at 07:43
  • 1
    This is no longer working. The order of iteration is not related to the current build type. – Petrakeas Feb 10 '22 at 11:18
  • @UnlikePluto Can you please delete or maybe add clarification that this answer is wrong?! As Peter said this is pure coincidence. – Farid Jul 21 '22 at 14:59
  • I run 'gradlew assembleDebug', and the code in {} of applicationVariants.all not invoke. – choufucai Jul 22 '22 at 09:32
2

This worked for me

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

You should getBuildConfigFields().get("MY_BUILD_TYPE").getValue())

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

GL

Braian Coronel
  • 22,105
  • 4
  • 57
  • 62
0

If you want to suffix the buildtype name to the versionname (like me) just add this line to the version name:

debug {
    versionNameSuffix "-debug"
}

This way you can identify the build type in the build name. And it works without declaring anything else.

jobbert
  • 3,297
  • 27
  • 43
0

Correct way for getting the current buildType being used during build in Kotlin programming language for android platform (logic is the same for 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)
                       }
         }
      }
   }
}
Jaki
  • 11
  • 5
0

I'm getting build type in this way:

BuildConfig.BUILD_TYPE

If you need to check what is the current build type, create an enum class in your utils package and use it in your if statement:

enum class Environment(val value: String) {
   RELEASE("release"),
   LOCAL("local"),
   STAGING("staging"),
   DEBUG("debug")
}

Your if/when statement:

if (BuildConfig.BUILD_TYPE == Environment.RELEASE.value) {
     //TODO
} else if(...)

or through when:

when(BuildConfig.BUILD_TYPE) {
   Environment.RELEASE.value -> { //TODO }
   Environment.LOCAL.value -> { // TODO }
   // etc.
}
Edhar Khimich
  • 1,468
  • 1
  • 17
  • 20
0

I checked other answers, nothing works. What's below will help. In your build.gradle (:app):

tasks.all { Task task ->
    if (task.name == "preDebugBuild") {
        doFirst {
            //for debug build
        }
    } else if (task.name == "preReleaseBuild") {
        doFirst {
            //for release build
        }
    }
}

dependencies {
    ...
}

Be aware, the code that you put inside will not be executed when you change the build variant, but when you build app.

0

Try like this in your gradle : It works fine for me

//get current build all params as string
def buildParams = getGradle().getStartParameter().toString().toLowerCase();

applicationVariants.all { variant ->
    variant.outputs.all {
        def typename = variant.buildType.name.toLowerCase();

        //and check build state in all variants
        if(buildParams.contains(typename)) {
            // finally, you get what you want.
        }
    }
}
-2

Here's the approach I used to detect the runtime build type without declaring any variables at build time.

def isCurrentBuildType(buildType) {
  return gradle.getStartParameter().taskNames.find({ it.endsWith(buildType) }) != null
}

print(isCurrentBuildType("Release")) //prints true if the current build type is release.

Note that the first letter should be capital (e.g. assembleRelease, bundleRelease)

Dumi Jay
  • 1,057
  • 10
  • 10
-3

You can get the exact build type by parsing your applicationVariants:

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

Kirtikumar A.
  • 4,140
  • 43
  • 43