Android flavor config file

485 views Asked by At

I have multiple flavors in my app. I have certain configs like the API endpoints and few other constants that change based on the flavor. I know we can pass them at build time using buildConfigs. But I do not want to add all these constants in my Build.gradle file(and pollute it). Can I have them in a separate config file and inject the values based on the build Flavor?

1

There are 1 answers

0
Mahdi Javaheri On

You can create your config files:

app/config/development.props

API_URL="https://yourapi.com"
TOKEN="SomeToken"

app/config/production.props

API_URL="https://yourapi.com"
TOKEN="SomeToken"

and pass them to your app's build.gradle like below:

android {
    flavorDimensions "full"
    productFlavors {
        development {
            dimension "full"
            applicationIdSuffix '.dev'
            versionNameSuffix "-dev"
            getProps('./config/development.props').each { p ->
                buildConfigField 'String', p.key, p.value
            }
        }
        production {
            dimension "full"
            applicationIdSuffix '.prod'
            versionNameSuffix "-prod"
            getProps('./config/production.props').each { p ->
                buildConfigField 'String', p.key, p.value
            }
        }
    }
}

def getProps(path) {
    Properties props = new Properties()
    props.load(new FileInputStream(file(path)))
    return props
}

Then access these fields in your kotlin/java code:

fun doSomething() {
  val apiUrl = BuildConfig.API_URL
  val token = BuildConfig.TOKEN
}