How to set variable according to gradle flavors

前提是你 提交于 2019-12-03 01:33:29

I found the solution:

First instead of def test specify a new field for all productFlavors

productFlavors.all {
    ext.dTest = null
}

Then this field is set in each flavor (code unchanged)

productFlavors {    
    flavorA {
        dTest = 1
    }

    flavorB {
        dTest = 2
    }    
}

And finally you can do this in the buildTypes

buildTypes {    
    all {
         productFlavors {
            all {
                ndk {
                    if (cFlags == null) { cFlags = "" }
                    cFlags = cFlags + " -DTEST="+dTest+" "
                }
            }
        }
    }
    debug {           
        minifyEnabled false
        ndk {
            if (cFlags == null) { cFlags = "" }
            cFlags = cFlags + " -DLOGGING=1 "
        }
    }
    release {
        minifyEnabled true
        proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'

        ndk {
            if (cFlags == null) { cFlags = "" }
            cFlags = cFlags + " -DLOGGING=0 "
        }
    }
}

Here the full file:

apply plugin: 'com.android.library'

android {
    compileSdkVersion 23
    buildToolsVersion "23.0.2"
    defaultPublishConfig "flavorARelease"
    publishNonDefault true

    defaultConfig {
        minSdkVersion 15
        targetSdkVersion 17

        ndk {
            moduleName "dTest"
            ldLibs "log"
        }
    }

    productFlavors.all {
        ext.dTest = null
    }

    productFlavors {    
        flavorA {
            dTest = 1
        }

        flavorB {
            dTest = 2
        }    
    }


    buildTypes {    
        all {
            productFlavors {
                all {
                    ndk {
                        if (cFlags == null) { cFlags = "" }
                        cFlags = cFlags + " -DTEST="+dTest+" "
                    }
                }
            }
        }
        debug {           
            minifyEnabled false
            ndk {
                if (cFlags == null) { cFlags = "" }
                cFlags = cFlags + " -DLOGGING=1 "
            }
        }
        release {
            minifyEnabled true
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'

            ndk {
                if (cFlags == null) { cFlags = "" }
                cFlags = cFlags + " -DLOGGING=0 "
            }
        }
    }

}

You can use buildConfigField

productFlavors {
    demo {
        buildConfigField "int", "FOO", "1"
        buildConfigField "String", "FOO_STRING", "\"foo1\""
    }
    full {
        buildConfigField "int", "FOO", "2"
        buildConfigField "String", "FOO_STRING", "\"foo2\""
    }
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!