How to access Gradle extra properties from Java?

Viewed 70

I'm doing some espresso tests for my application and i'm interacting with a real API from my tests. So, I'm trying to read those API credentials from some environment variables:

Let's say I'm using Netflix API. I declare the credentials in bash_profile on MAC:

export NETFLIX_ID='123'
export NETFLIX_TOKEN='xxx'
launchctl setenv NETFLIX_ID $NETFLIX_ID
launchctl setenv NETFLIX_TOKEN $NETFLIX_TOKEN

Now on Gradle, I create some extra properties, like this:

ext {
  netflixId = System.getenv("NETFLIX_ID")
  netflixToken = System.getenv("NETFLIX_TOKEN")
}

If I print netflixId and netflixToken the credentials are printed correctly, meaning System.getenv() is working.

What I'm trying to do now is to read those extra properties from Java code. Do you know if there is a way to do that? or a better approach? any help would be appreciated

1 Answers

You can build the values of the environment variables into your application. You can put those in build config fields in build.gradle:

android {
    defaultConfig {
        buildConfigField "String", "NETFLIX_ID", "\"" + System.getenv('NETFLIX_ID') + "\""
    }
}

These values then end up in the compile time generated BuildConfig class in the package corresponding to that gradle module's AndroidManifest package, and you can then use BuildConfig.NETFLIX_ID to use the value.

Related