问题
I have 3 product flavors (flavor1, flavor2, flavor3) in my app. flavor1 and flavor2 share some of the dependencies related to ads.
Is there a way to bundle the ad related dependencies to a gradle dimension or configuration and add that to flavor1 and flavor2 without duplicating the compileFlavor1 and compileFlavor2 lines in my build.gradle?
This is part of my current gradle. This works. But, I'm wondering if there is a better way to do this? So, I don't have to repeat the ad dependencies for each flavor.
android {
productFlavors {
flavor1 {}
flavor2 {}
flavor3 {}
}
sourceSets {
main {}
flavor1.java.srcDir 'common/ads/java' <--- shared sourceSet
flavor2.java.srcDir 'common/ads/java'
flavor3.java.srcDir 'common/no_ads/java'
}
}
dependencies {
compile 'dependency1'
compile 'dependency2'
compileFlavor1 'dependency3' <----- Same list
compileFlavor1 'dependency4'
compileFlavor1 'dependency5'
compileFlavor2 'dependency3' <------ Same list
compileFlavor2 'dependency4'
compileFlavor2 'dependency5
}
回答1:
This is what we did to share directories between flavors:
sourceSets {
main {
java.srcDirs = ['src/main/java']
res.srcDirs = ['src/main/res']
assets.srcDirs = ['src/main/assets']
}
production {
java.srcDirs = ['src/main/java', 'src/shared/java']
res.srcDirs = ['src/main/res', 'src/shared/res']
assets.srcDirs = ['src/main/assets', 'src/shared/assets']
}
logger {
java.srcDirs = ['src/main/java', 'src/shared/java', 'src/mock/java']
res.srcDirs = ['src/main/res', 'src/shared/res']
assets.srcDirs = ['src/main/assets', 'src/shared/assets']
}
nowav {
java.srcDirs = ['src/main/java', 'src/nowav/java', 'src/mock/java']
res.srcDirs = ['src/main/res', 'src/nowav/res']
assets.srcDirs = ['src/main/assets', 'src/nowav/assets']
}
}
回答2:
Solution for sharing dependencies between flavors (updated for implementation
which has now replaced compile
):
Since implementation
, flavor1Implementation
, flavor2Implementation
, etc. are all in fact themselves Configurations you can actually apply an inheritance relationship between these steps in the build process.
Therefore in this case you can specify your shared dependencies, and dependencies for flavor1
only:
dependencies {
implementation 'dependency1'
implementation 'dependency2'
flavor1Implementation 'dependency3'
flavor1Implementation 'dependency4'
flavor1Implementation 'dependency5'
}
...And then simply allow flavor2Implementation
to inherit from flavor1Implementation
:
configurations.flavor2Implementation.extendsFrom(flavor1Implementation)
This can also be used to define more complex relationships between flavors, and multiple inheritance is supported, e.g:
configurations {
flavor3Implementation.extendsFrom(
flavor1Implementation,
flavor2Implementation
)
}
(Finally, just a note that sharing code between flavors should be continued to be handled with sourceSets
as per the original question.)
来源:https://stackoverflow.com/questions/45579298/android-gradle-sharing-dependencies-between-product-flavors