简体   繁体   中英

How to use BuildConfig.DEBUG as task variable in build.gradle on Android Studio 4.0?

I have a custom task that required to check if the current build is debug or release, and then use the corresponding classpath.

The normal task definition:

task custom_java_task(type: JavaExec) {
    classpath "build/intermediates/javac/debug/classes/"
    main = "com.testapp.JavaTaskTest"
    args "test", "${projectDir}"
}

The task definition needs to check BuildConfig.DEBUG and set the different value for classpath:

task custom_java_task(type: JavaExec) {
    classpath BuildConfig.DEBUG ? "build/intermediates/javac/debug/classes/" : "build/intermediates/javac/release/classes/"
    main = "com.testapp.JavaTaskTest"
    args "test", "${projectDir}"
}

The build will fail with the following error:

Could not get unknown property 'BuildConfig' for task ':app:custom_java_task' of type org.gradle.api.tasks.JavaExec.

Thanks.

BuildConfig is generated set of properties that cannot be used from within gradle scripts. It is actually generated based on your build.gradle

But there are some ways to achieve what you want for example like this:

First in project level build.gradle under buildscript you can define the function / method and name ti however you want (eg. doStuff )

buildscript {
    ...
    ext.doStuff = { buildType ->
        // do stuff based on buildType param
    }
    ...
}

Than in your module level build.gradle, simply do

android {
    ...
    buildTypes {
        debug {
            ...
            doStuff("debug")
        }
        release {
            ...
            doStuff("release")
        }
    }
    ...
}

Now this is just to give you a hint on the abilities of build.gradle files, you can build further from this.

Cheers

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM