问题描述
我想根据当前的 buildType 在 Android Gradle 项目中动态添加依赖项.我知道我可以在依赖项中指定 buildType:
I want to dynamically add a dependency in an Android Gradle project based on the current buildType. I know I can specify the buildType in the dependency:
compile project(path: ':lib1', configuration: 'debug')
但是如何使用当前的 buildType 来指定我要导入的库的哪个变体,以便调试或发布版本自动导入库的调试或发布变体?我想要的是这样的(其中 currentBuildType 是一个包含当前使用的 buildType 名称的变量):
But how can I use the current buildType to specify which variant of the library I want to import, so that a debug or release build automatically imports the debug or release variant of the library? What I want is something like this (where currentBuildType is a variable containing the name of the currently used buildType):
compile project(path: ':lib1', configuration: currentBuildType)
我要导入的库项目设置了publishNonDefault true
,所以所有的buildTypes都被发布了.
The library project I want to import has set publishNonDefault true
, so all buildTypes are published.
推荐答案
我在 Gradle 的配置阶段找不到一个干净的方法来获取当前的构建类型.相反,我像这样分别定义每种构建类型的依赖关系:
I could not find a clean way to get the current build type during the configuration phase of Gradle. Instead I define the dependency for each build type separately like that:
debugCompile project(path: ':lib1', configuration: 'debug')
releaseCompile project(path: ':lib1', configuration: 'release')
如果您有许多构建类型和许多项目依赖项,这可能会变得非常冗长,但可以添加一个函数以使依赖项成为单行.您需要将此添加到您的主要 Gradle 构建文件中:
If you have many build types and many project dependencies this can get very verbose, but it is possible to add a function to make the dependency a one-liner. You need to add this to your main Gradle build file:
subprojects {
android {
dependencies.metaClass.allCompile { dependency ->
buildTypes.each { buildType ->
"${buildType.name}Compile" project(path: ":${dependency.name}", configuration: buildType.name)
}
}
}
}
然后您可以像这样在 Gradle 模块中添加项目依赖项:
Then you can add project dependencies in your Gradle modules like this:
allCompile project(':lib1')
如果您还使用构建风格,则必须调整解决方案.有关该功能的文档,请参阅此链接:http://tools.android.com/tech-docs/new-build-system/user-guide#TOC-Library-Publication
If you also use build flavors you would have to adapt the solution. See this link for a documentation of the feature: http://tools.android.com/tech-docs/new-build-system/user-guide#TOC-Library-Publication
请注意,Android 团队正在努力改进此行为:https://code.google.com/p/android/issues/detail?id=52962
Please note that the Android team is working on an improvement for this behaviour: https://code.google.com/p/android/issues/detail?id=52962
这篇关于如何在 Android Gradle 配置中获取当前的 buildType的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!