ichthyocentaurs
ichthyocentaurs

Reputation: 2175

How to call a gradle task from productflavor

I need to enable Fabric for different build environments and also take into account whether the apk has been built using Android Studio or a CI server (jenkins) in our case. Approach that I am thinking of using is:

defaultConfig {
    applicationId "com.pack.proj"
    minSdkVersion 19
    targetSdkVersion 23
    versionCode 12
    ext.buildNumber = System.getenv("BUILD_NUMBER") ?: "dev"
    versionName "1.2.$buildNumber"
    signingConfig signingConfigs.inspection
}

productFlavors {
        dev1 {
            resValue 'string', 'app_name', 'App Name'
            resValue 'string', 'base_url', 'http://dev1.server.in/'
            buildConfigField 'boolean', 'USE_FABRIC', 'true'

        }
        dev2 {
            resValue 'string', 'app_name', 'App Name'
            resValue 'string', 'base_url', 'http://dev2.server.in/'
            // ********HOW DO I CALL THE TASK 'enableFabric' FROM HERE*********
        }
}

task enableFabric{
    if(versionName.contains('dev'))
        buildConfigField 'boolean', 'USE_FABRIC', 'false'
    else
        buildConfigField 'boolean', 'USE_FABRIC', 'true'
}

Now my questions are

  1. How do I call the task enableFabric from dev1 and dev2 product flavors?
  2. And when I run the gradle script I get the error that versionName is unrecognised property in task enableFabric?
  3. also buildConfigField 'boolean', 'USE_FABRIC', 'true' when used in the defaultConfig does not work for me. when I use

    if(BuildConfig.USE_FABRIC == true){ // DO something }

in the Java code.

Upvotes: 2

Views: 254

Answers (1)

eriuzo
eriuzo

Reputation: 1687

put the if else directly in dev2. or if you plan to use it more than once turn it into a function instead of task

example:

productFlavors {
    dev1 {
        resValue 'string', 'app_name', 'App Name'
        resValue 'string', 'base_url', 'http://dev1.server.in/'
        buildConfigField 'boolean', 'USE_FABRIC', 'true'

    }
    dev2 {
        resValue 'string', 'app_name', 'App Name'
        resValue 'string', 'base_url', 'http://dev2.server.in/'
        buildConfigField 'boolean', 'USE_FABRIC', useFabric()
    }
}

outside of your android block, do something like

def useFabric() {
    if (versionName.contains('dev')) 
       return false;
    else return true;
}

Upvotes: 1

Related Questions