How to Create Custom Environment Variable for Your Android App via generated from build.gradle

How to Create Custom Environment Variable for Your Android App via generated from build.gradle
Photo by Rohan / Unsplash

I am building an android app which has an open ad unit. It is suggested to use test ad unit id during developing stage. Hence I hard coded the test ad unit id in my code to debug the open app ad. When the app is ready to release, I have to replace the ad unit id to the real one registered on AdMob. Um. Is there a way to generate the ad unit id during build time? For debug build, it will be assigned with the test ad unit id, the real ad unit id will be replaced release build. By doing so, the code will keep the same to debug and release build.

use build.gradle (module:app)

The answer is yes, you can Share custom fields and resource values with your app's code

At build time, Gradle generates the BuildConfig class so your app code can inspect information about the current build. You can also add custom fields to the BuildConfig class from your Gradle build configuration file using the buildConfigField() method and access those values in your app's runtime code. Likewise, you can add app resource values with resValue().

Add APP_OPEN_AD_UNIT_ID build config example

edit your app/build.gradle, add your custom build config field for different build types. e.g.:

    buildTypes {
        debug {
            buildConfigField "String", "APP_OPEN_AD_UNIT_ID", "\"ca-app-pub-3940256099942544/3419835294\""
        release {
            buildConfigField "String", "APP_OPEN_AD_UNIT_ID", "\"ca-app-pub-real/ad-unit-id\""

After you run gradle build, you will see the field APP_OPEN_AD_UNIT_ID defined in (generated during build time).

Access BuildConfig.APP_OPEN_AD_UNIT_ID

import com.lengerrong.coca.BuildConfig;

                context, BuildConfig.APP_OPEN_AD_UNIT_ID, request,


Gradle tips and recipes | Android Developers
Gradle and the Android plugin for Gradle provide a flexible way to compile, build, and package your Android app or library.

Subscribe to Post, Code and Quiet Time.

Don’t miss out on the latest issues. Sign up now to get access to the library of members-only issues.