2

We have an App in Kotlin ( Android Stdio) which has different constants by environment. We are using Constants.kt const val IMAGES_API = "https://localhost:3000/v1/images" and we want to use the same variable in staging/qa/prod. The App is building in Kotlin and we are using gradle (groovy scripts) to compiling and packing the different environment staging/qa/prod. My first approach has been to create this properties on the gradle.properties and load the properties on the build.gradle file like this :

def loadProperties() {
def props = new Properties()
file("gradle.properties").withInputStream { props.load(it) }
def config = props
project.ext.config = config
}

And when I run gradle I can see the new properties, but I don't know how to get this value inside the App ( in the kotlin code).

My only idea is to create a task on build.gradle to copy a Constants.kt file by environment. But, I don't think, it's a good practice. I think, there must be another way to set different variables in the App. Please, can anybody help me with this?

  • try use buildConfigFields in your gradle here android { defaultConfig { buildConfigField "String", 'ENDPOINT', "\"https://localhost/\"" Then inject your Config singleton anywhere in application and get constant from here by name. Config.ENDPOINT in that case. – rost Nov 12 '20 at 10:04

1 Answers1

2

What you want is to configure build types in your app module's gradle file with buildConfigField in each:

 buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'

            buildConfigField "String", "SERVER_URL", '"http://prod.this-is-so-fake.com"'
        }

        debug {
            applicationIdSuffix ".debug"
            debuggable true

            buildConfigField "String", "SERVER_URL", '"http://test.this-is-so-fake.com"'
        }

        /**
         * The `initWith` property allows you to copy configurations from other build types,
         * then configure only the settings you want to change. This one copies the debug build
         * type, and then changes the application ID.
         */
        staging {
            initWith debug
            applicationIdSuffix ".debugStaging"

            buildConfigField "String", "SERVER_URL", '"http://prod.this-is-so-fake.com"'
        }
    }

In code, you can refer to BuildConfig.SERVER_URL, and it will be populated with the string based on the build type you choose at compile time.

You can build different apk/app bundles to distribute.

Referencing this answer .

EDIT As an aside, in real life I have found this approach to be... annoying. It is easier to bundle inside the app a toggle that allows QA to switch between environments. This way you only have one bundle to deal with.

P Fuster
  • 2,224
  • 1
  • 20
  • 30