我怎样才能获得"当前"在build.gradle文件中构建类型?

时间:2016-12-12 13:04:08

标签: android-gradle

我想做这样的事情:

 productFlavors {
        favor1 {
            buildConfigField 'String', 'SERVICE_URL', BuildConfig.BUILD_TYPE.equals("test") ?
                    '"oneThing"' :
                    '"anotherThing"'
        }
        //more flavors
}

但显然我在BuildConfig.BUILD_TYPE.equals("test") ?时遇到错误。有没有办法做到这一点?

1 个答案:

答案 0 :(得分:1)

尝试以下操作:

   applicationVariants.all { variant ->
        def PRODUCT_IDENTIFIER = "PRODUCT_IDENTIFIER"
        def SERVER_URL = "SERVER_URL"

        def flavor = variant.productFlavors[0].name
        def buildType = variant.buildType.name

        if( flavor == "Demo") {
            buildConfigField "String", "PRODUCT_IDENTIFIER", "\"identifier_DEMO\""
        }
        else if( flavor == "Test") {
            buildConfigField "String", "PRODUCT_IDENTIFIER", "\"identifier_TEST\""
        }

        if( buildType == "debug" ) {
            variant.buildConfigField "String", "SERVER_URL", "\"https://myserver.com/debug\""
        }
        else if( buildType == "release" ) {
            variant.buildConfigField "String", "SERVER_URL", "\"https://myserver.com/release\""
        }
    }

然后,从Java角度来看:

String identifier = BuildConfig.HOTEL_IDENTIFIER;
String serverUrl = BuildConfig.SERVER_URL

将导致:

DemoDebug

identifier -> "identifier_DEMO"
serverUrl -> "https://myserver.com/debug"

DemoRelease

identifier -> "identifier_DEMO"
serverUrl -> "https://myserver.com/release"

TestDebug

identifier -> "identifier_TEST"
serverUrl -> "https://myserver.com/debug"

TestRelease

identifier -> "identifier_TEST"
serverUrl -> "https://myserver.com/release"