How to get the build variant at runtime in Android Studio?

前端 未结 5 1101
别那么骄傲
别那么骄傲 2020-12-02 22:00

I\'d like to get the build variant during runtime, is this possible without any extra config or code?

5条回答
  •  醉酒成梦
    2020-12-02 22:14

    Here is an example to define and get BuildConfig for different flavor

    android {
    
        defaultConfig {
            ...
        buildTypes {
            ...
        }
    
        flavorDimensions "default"
        productFlavors {
    
            develop {
                applicationIdSuffix ".dev"
                versionNameSuffix "-dev"
            }
    
            staging {
                applicationIdSuffix ".stg"
                versionNameSuffix "-stg"
            }
    
            production {
                applicationIdSuffix ""
                versionNameSuffix ""
            }
        }
    
        applicationVariants.all { variant ->
    
            def BASE_URL = ""
    
            if (variant.getName().contains("develop")) {
                BASE_URL = "https://localhost:8080.com/"
            } else if (variant.getName().contains("staging")) {
                BASE_URL = "https://stagingdomain.com/"
            } else if (variant.getName().contains("production")) {
                BASE_URL = "https://productdomain.com/"
            }
            variant.buildConfigField "String", "BASE_URL", "\"${BASE_URL}\""
    
        }
    }
    

    Using

    BuildConfig.BASE_URL

提交回复
热议问题