問題描述
我想根據(jù)當前的 buildType 在 Android Gradle 項目中動態(tài)添加依賴項.我知道我可以在依賴項中指定 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 來指定我要導(dǎo)入的庫的哪個變體,以便調(diào)試或發(fā)布版本自動導(dǎo)入庫的調(diào)試或發(fā)布變體?我想要的是這樣的(其中 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)
我要導(dǎo)入的庫項目設(shè)置了publishNonDefault true
,所以所有的buildTypes都被發(fā)布了.
The library project I want to import has set publishNonDefault true
, so all buildTypes are published.
推薦答案
我在 Gradle 的配置階段找不到一個干凈的方法來獲取當前的構(gòu)建類型.相反,我像這樣分別定義每種構(gòu)建類型的依賴關(guān)系:
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')
如果您有許多構(gòu)建類型和許多項目依賴項,這可能會變得非常冗長,但可以添加一個函數(shù)以使依賴項成為單行.您需要將此添加到您的主要 Gradle 構(gòu)建文件中:
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')
如果您還使用構(gòu)建風(fēng)格,則必須調(diào)整解決方案.有關(guān)該功能的文檔,請參閱此鏈接: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
這篇關(guān)于如何在 Android Gradle 配置中獲取當前的 buildType的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網(wǎng)!