Environment variables, BuildConfig, Gradle.properties and Android Studio

Hello guys,

Today I will post some simple steps to have some environment variables in your android studio project. So, if you have some confidential data to use in your android tests, you can hide the password, username or if you just want to have some environment variables separated from your project, just follow these steps:

So, let’s start:

Screen Shot 2015-09-17 at 21.58.28

  • In your gradle.properties create the environment variables (You can find this file inside of your Android Studio project or in your /Users/Your Username/.gradle)
testUsername="username"
testPassword="password"
  • In your build.gradle file (Remember, you can have many build.gradle file, so first try to find the one that you want to share with all projects or the one which you will use only in your project > buildTypes > debug, as it is showed in the structure below). The “USERNAME” and “PASSWORD” will be the variables in your code and the testUsername and testPassword should be the same variable which you are using in your gradle.properties file (above).
android {
buildTypes {
  debug {
    ...
    buildConfigField "String", "USERNAME", testUsername
    buildConfigField "String", "PASSWORD", testPassword
   }

  release {
   ...
    }
  }
}
  • After this, you need to sync your gradle.
  • And in your code, just call the variables like this:
BuildConfig.USERNAME
BuildConfig.PASSWORD

I am using gradle 2.4 and androidStudio 1.3.2.

Thank you, see you next week 🙂

Resources:

http://examples.javacodegeeks.com/core-java/gradle/gradle-properties-build-configuration-example/

http://www.rainbowbreeze.it/environmental-variables-api-key-and-secret-buildconfig-and-android-studio/

5 thoughts on “Environment variables, BuildConfig, Gradle.properties and Android Studio

  1. it’s ok thanks for this tutorial, but with release mode for obfuscation and after genereted a signed apk, and after decompile, the strings values are not hiding ! so waht can i do to hode my strings for obfuscation ?

  2. Hello terrific website! Does running a blog like this take
    a great deal of work? I’ve no expertise in computer programming however I was hoping
    to start my own blog soon. Anyways, should you have any ideas
    or tips for new blog owners please share. I understand this is off subject but
    I simply needed to ask. Thank you!

Leave a comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.