How to get a resource value in build.gradle?

If you are only trying to set the App Label (or other manifest values) you can solve this with manifest placeholders.

android {

    productFlavors {
        Foo {
             applicationId "com.myexample.foo"
             manifestPlaceholders.appName = "Foo"
        }

        Bar {
             applicationId "com.myexample.bar"
             manifestPlaceholders.appName = "Bar"
        }
    }

    buildTypes {
        release {
            manifestPlaceholders.appNameSuffix =""
        }

        debug {
            manifestPlaceholders.appNameSuffix =".Debug"
            applicationIdSuffix ".debug"
        }
    }
}

Then in your Android Manifest you simply use both placeholders for your app name (or other values)

 <application
        android:label="${appName}${appNameSuffix}"
        ...
 </application>

This allow you to install all 4 variants side by side on a single device as well as give them different names in the app drawer / launcher.

EDIT 11/22/2019

Updated how placeholders values are set based on feedback from @javaxian


To have an alternative version of a resource in debug builds you can use the debug source set.

strings.xml can be found under following path src/main/res/values, which means it's in the main source set. If you create a new directory src/debug/res/values you can put a new strings.xml file in there with values that should be overridden in debug builds. For example:

<?xml version="1.0" encoding="utf-8"?>
<resources>
    <string name="app_name">My Application Debug</string>
</resources>

This will replace whatever value app_name has in your main file. You don't have to duplicate all the strings in here - ones you don't include here are simply taken from the main file.


You can check the build variants like this

Define values in gradle

buildTypes {
    debug{
        buildConfigField "String", "Your_string_key", '"yourkeyvalue"'
        buildConfigField "String", "SOCKET_URL", '"some text"'
        buildConfigField "Boolean", "LOG", 'true'
    }
    release {
        buildConfigField "String", "Your_string_key", '"release text"'
        buildConfigField "String", "SOCKET_URL", '"release text"'
        buildConfigField "Boolean", "LOG", 'false'

    }
}

And to access those values using build variants:

 if(!BuildConfig.LOG)
      // do something with the boolean value

Or

view.setText(BuildConfig.yourkeyvalue);