Today I want to tell you about an interesting way of managing env variables (those things that you usually put in your build.gradle ).

Disclaimer: I’m not pretending that this is the most right way to do this (or even right at all), but it solved the problem i faced on my project.

Environment & Variables

First of all, let’s define what an Environment Variable means in Android app. Usually it’s a String or a boolean flag that changes depending on the environment you’re running your app in. Imagine you have two different servers for your API:

development server, where main development and testing happens

production server, where your app goes live

What’s the common way to put URLs for those servers in Android? Yes, it’s BuildConfig

After setting up your build.gradle like that and syncing the project, you can access this in your code with BuildConfig.BASE_URL . BASE_URL here is your environment variable. And it’s gonna be different depending on which build type you’ve used.

Build script vs. code

This is a perfectly fine approach and works for most of the projects.

But not so long ago I got an interesting task from my lead: “We should be able to switch from dev to prod and back with a tap of a button”.

And it turns out that I can’t do it easily with the BuildConfig approach: BuildConfig class is generated during compile time, all the variables set depending on selected build type and can’t be changed.

That’s being said, I decided to move all my environment variables from build.gradle to the actual code.

First things first, let’s describe our environment variables (and keep it short for this article):

After that we need to define all the environments for our app

And as a final step, we are going to write an EnvironmentManager class, which will allow us to get any env variable and also switch environments easily.

(Pay attention to comments in the code snippet down there, they explain what’s going on 👍)

The last thing we need to do is to connect our buildTypes to environments described in the code in order to use right variables for each build type in case when nothing was selected through the code. For this purpose, we’ve defined one buildConfig property: DEFAULT_ENV

So, for the fresh install, your app gonna use environment set in DEFAULT_ENV

That’s all! Now you can use the EnvironmentManager like this:

If you like the post, please give some claps 👏

and follow me on twitter