Variable in Android Studio Gradle

December 20, 2018
Declare variable for manifest in Gradle build configuration

Declare variable in module build.gradle.

dependencies {
    def dagger_version = "2.15"

    implementation "com.google.dagger:dagger:$dagger_version"
    implementation "com.google.dagger:dagger-android:$dagger_version"
    implementation "com.google.dagger:dagger-android-support:$dagger_version"
    kapt "com.google.dagger:dagger-android-processor:$dagger_version"
    kapt "com.google.dagger:dagger-compiler:$dagger_version"
}

Delcare variable in project build.gradle and refer to it in module build.gradle.

Project build.gradle.

buildscript {
    ext {
        dagger_version = '2.15'
    }
}

Module build.gradle.

dependencies {
    implementation "com.google.dagger:dagger:$dagger_version"
    implementation "com.google.dagger:dagger-android:$dagger_version"
    implementation "com.google.dagger:dagger-android-support:$dagger_version"
    kapt "com.google.dagger:dagger-android-processor:$dagger_version"
    kapt "com.google.dagger:dagger-compiler:$dagger_version"
}

Declare variable in module build.gradle and refer to it in AndroidManifest.xml.

Module build.gradle.

android {
    buildTypes {
        debug {
            manifestPlaceholders = [crashlyticsEnabled: false, analyticsEnabled: false]
        }
        release {
            manifestPlaceholders = [crashlyticsEnabled: true, analyticsEnabled: true]
        }
    }
}

AndroidManifest.xml.

<manifest ...>
    <application ...>

        <meta-data
            android:name="firebase_crashlytics_collection_enabled"
            android:value="${crashlyticsEnabled}" />

        <meta-data
            android:name="firebase_analytics_collection_enabled"
            android:value="${analyticsEnabled}" />
    
    </application>
</manifest>
This work is licensed under a
Creative Commons Attribution-NonCommercial 4.0 International License.