Defining Constants in Gradle

Every android app has some global constants values such as Base URL, API keys etc. Usually, developers define these constants in any AppConstants.java file as static final variables, or they define these in strings.xml file.



But, in Android, there’s a better and more secure way for this. You can define the constants in app’s build.gradle file like this:

apply plugin: 'com.android.application'

// ...

android {
  // ... 
  
  buildTypes {
    debug {
      // ...
      buildConfigField "String", "SERVER_URL", "http://mybase.url.com/debug/"
    }
    release {
      // ...
      buildConfigField "String", "SERVER_URL", "http://mybase.url.com/release/"
    }
  }
}

// ...

Now, you can access it in the code like this:

var myUrl = BuildConfig.SERVER_URL
// Do stuff with myUrl here

If you liked this article, you can read my new articles below:


profile card
Wajahat Karim
🌍 Making the world a better place, one app at a time.
🔥 Google Developer Expert (GDE) in Android . 📱 Professional Android Developer with ~10 years experience. 💻 Creator of various Open Source libraries on Android . 📝 Author of two technical books and 100+ articles on Android. 🎤 A passionate Public Speaker giving talks all over the world.
Author's picture

Wajahat Karim

🔥 Google Dev Expert (GDE) in Android .
📱 Android Dev. 💻 Open Source Contributor . 📝 Technical Writer . 🎤 Public Speaker

Senior Android Developer

Karachi, Pakistan