問題背景
項目中有2個 module, 其中 B 依賴 A, 起初兩個 module 都沒有定義 flavor, 由于業(yè)務(wù)發(fā)展, 給底層的 module A 定義了兩個 flavor(本文中使用 flavor1 和 flavor2 表示), 在編譯時, gradle 編譯錯誤提示如下:
* What went wrong:
Could not determine the dependencies of task ':B:compileReleaseRenderscript'.
> Could not resolve all task dependencies for configuration ':B:releaseCompileClasspath'.
> Could not resolve project :A.
Required by:
project :B
> Cannot choose between the following configurations of project :A:
- flavor1ReleaseApiElements
- BReleaseApiElements
All of them match the consumer attributes:
- Configuration 'flavor1ReleaseApiElements':
- Required com.android.build.api.attributes.BuildTypeAttr 'release' and found compatible value 'release'.
- Found com.android.build.api.attributes.VariantAttr 'flavor1Release' but wasn't required.
- Required com.android.build.gradle.internal.dependency.AndroidTypeAttr 'Aar' and found compatible value 'Aar'.
- Found default 'flavor1' but wasn't required.
- Required org.gradle.usage 'java-api' and found compatible value 'java-api'.
- Required org.jetbrains.kotlin.platform.type 'androidJvm' and found compatible value 'androidJvm'.
- Configuration 'BReleaseApiElements':
- Required com.android.build.api.attributes.BuildTypeAttr 'release' and found compatible value 'release'.
- Found com.android.build.api.attributes.VariantAttr 'BRelease' but wasn't required.
- Required com.android.build.gradle.internal.dependency.AndroidTypeAttr 'Aar' and found compatible value 'Aar'.
- Found default 'B' but wasn't required.
- Required org.gradle.usage 'java-api' and found compatible value 'java-api'.
- Required org.jetbrains.kotlin.platform.type 'androidJvm' and found compatible value 'androidJvm'.
其中, module A 中的 flavor 定義如下:
flavorDimensions "default"
productFlavors {
flavor1 {
dimension "default"
}
flavor2 {
dimension "default"
}
}
module B 中未定義任何 flavor.
解決方法
首先說明下原因: module B 依賴 module A, A 有2個 flavor 定義, B 沒有 flavor 定義, B 在編譯期無法知道該依賴 module A 的哪一個 flavor.
要解決這個問題, 需要給 module B 指定應(yīng)該依賴 module A 的哪一個 flavor. 有兩種方法:
方法一:
給 module B 定義一個 module A 中同名的 flavor, 如:
flavorDimensions "default"
productFlavors {
flavor1 {
dimension "default"
}
}
gradle 會自動根據(jù) flavor name 匹配依賴 module 中對應(yīng)的 flavor, 這里要注意, flavorDimensions 也必須與依賴 module 中的 flavorDimensions 一致.
方法二:
module B 中的 flavor 與 module A 中的所有 flavor 都不匹配, 可以通過 matchingFallbacks 指定.
flavorDimensions "default"
productFlavors {
flavor3 {
dimension "default"
matchingFallbacks = ['flavor1']
}
}
matchingFallbacks 其他作用
matchingFallbacks 不僅可以用于配置 productFlavors, 還可以配置 build type, 比如, 如果module B 有一個特殊的 build type, 然后 module A 中只有 debug 和 release 兩種 build type, 會有同樣類似的編譯錯誤. 該問題依然可以通過 matchingFallbacks 指定 build type 類型來解決, 如 :
buildTypes {
releaseQA {
matchingFallbacks = ['release']
}
}