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:


Wajahat Karim is Pakistan’s first Google Developer Expert in Android. As an experience Android developer, he deeply cares about it and keeps writing and speaking about it. He has written two worldwide 300+ pages books on Android development with more than 100 articles around the internet either on his website or his Medium publications. He is also a passionate contributor in open source and has created many Android libraries used by thousands of developers in their apps worldwide. As active public speaker, he spends lots of time giving talks in conferences and motivating people on Android development. You can find Wajahat most active on Twitter @WajahatKarim where he regularly shares all the good stuff about Android and community building.

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