Search code examples
androidgradleandroid-gradle-pluginandroid-resourcesandroid-flavors

How to use final resolved applicationId in build.gradle


Say I have the following build.gradle

android{
    defaultConfig{
        applicationId "com.example.base"
    }
    buildTypes{
        release{
            minifyEnabled true
        }
        debug{
            applicationIdSuffix ".dev"
            minifyEnabled false
        }
    }
    productFlavors{
        free{
            applicationId "com.example.free"
        }
        paid{
            applicationId "com.example.paid"
        }
    }
}

I want to add the resulting application id to strings.xml, like this:

resValue "string", "app_package", applicationId

So I can then use this value in intents targetPackage defined in preferences xml

But the value changes depending on what block I put that line in:

  • defaultConfig -> "com.example.base" (always the base Id, useless)
  • productFlavours.free -> "com.example.free" (problem is this does not change to "com.example.free.dev" for debug builds)
  • productFlavours -> Error, does not build
  • buildTypes.debug -> Error, does not build

By using the applicationIdSuffix, I need gradle to resolve the final id before I can use it. How do I do that?


Solution

  • Add this after productFlavors within android DSL:

    applicationVariants.all { variant ->
        variant.resValue  "string", "app_package", variant.applicationId
    }
    

    In freeDebug build this will be added in app/intermediates/res/merged/free/debug/values/values.xml:

    <string name="app_package" translatable="false">com.example.free.dev</string>
    

    In paidDebug:

    <string name="app_package" translatable="false">com.example.paid.dev</string>