How can I access a BuildConfig value in my AndroidManifest.xml file? How can I access a BuildConfig value in my AndroidManifest.xml file? android android

How can I access a BuildConfig value in my AndroidManifest.xml file?


Replace

buildConfigField "long", "FACEBOOK_APP_ID", FACEBOOK_APP_ID

with

resValue "string", "FACEBOOK_APP_ID", FACEBOOK_APP_ID

then rebuild your project (Android Studio -> Build -> Rebuild Project).

The two commands both produce generated values - consisting of Java constants in the first case, and Android resources in the second - during project builds, but the second method will generate a string resource value that can be accessed using the @string/FACEBOOK_APP_ID syntax. This means it can be used in the manifest as well as in code.


Another way to access Gradle Build Config values from your AndroidManifest.xml is through placeholders like this:

android {    defaultConfig {        manifestPlaceholders = [ facebookAppId:"someId..."]    }    productFlavors {        flavor1 {        }        flavor2 {            manifestPlaceholders = [ facebookAppId:"anotherId..." ]        }    }}

and then in your manifest:

<meta-data android:name="com.facebook.sdk.ApplicationId" android:value="${facebookAppId}"/> 

See more details here: https://developer.android.com/studio/build/manifest-build-variables.html

(Old link just for reference: http://tools.android.com/tech-docs/new-build-system/user-guide/manifest-merger)


note: when you use resValue the value can accidentally be overridden by the strings resource file (e.g. for another language)

To get a true constant value that you can use in the manifest and in java-code, use both manifestPlaceholders and buildConfigField: e.g.

android {    defaultConfig {        def addConstant = {constantName, constantValue ->            manifestPlaceholders += [ (constantName):constantValue]            buildConfigField "String", "${constantName}", "\"${constantValue}\""        }        addConstant("FACEBOOK_APP_ID", "xxxxx")    }

access in the manifest file:

<meta-data android:name="com.facebook.sdk.ApplicationId" android:value="${FACEBOOK_APP_ID}"/>

from java:

BuildConfig.FACEBOOK_APP_ID

If the constant value needs to be buildType-specific, the helper addConstant needs to be tweaked (to work with groovy closure semantics), e.g.,

buildTypes {    def addConstantTo = {target, constantName, constantValue ->        target.manifestPlaceholders += [ (constantName):constantValue]        target.buildConfigField "String", "${constantName}", "\"${constantValue}\""    }    debug {        addConstantTo(owner,"FACEBOOK_APP_ID", "xxxxx-debug")    }    release {        addConstantTo(owner,"FACEBOOK_APP_ID", "xxxxx-release")    }