如何在build.gradle中使用最终解析的applicationId

roc*_*cko 4 android gradle android-resources android-gradle-plugin android-flavors

说我有以下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"
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

我想将生成的应用程序ID添加到strings.xml,如下所示:

resValue "string", "app_package", applicationId
Run Code Online (Sandbox Code Playgroud)

因此,我可以targetPackage在首选项xml中定义的意图中使用此值

但是该值会根据我在该行中放置的内容而有所不同:

  • defaultConfig->“ com.example.base”(始终为基本ID,无用)
  • productFlavours.free->“ com.example.free”(问题是调试构建不会更改为“ com.example.free.dev”)
  • productFlavours->错误,无法构建
  • buildTypes.debug->错误,无法构建

通过使用applicationIdSuffix,我需要gradle才能解析最终的ID,然后才能使用它。我怎么做?

azi*_*ian 6

productFlavorsandroidDSL中添加以下内容:

applicationVariants.all { variant ->
    variant.resValue  "string", "app_package", variant.applicationId
}
Run Code Online (Sandbox Code Playgroud)

freeDebug构建中将添加到app/intermediates/res/merged/free/debug/values/values.xml

<string name="app_package" translatable="false">com.example.free.dev</string>
Run Code Online (Sandbox Code Playgroud)

paidDebug

<string name="app_package" translatable="false">com.example.paid.dev</string>
Run Code Online (Sandbox Code Playgroud)