Can anyone suggest, how can we add a dependency at build time in android gradle based on some condition like:
dependencies{
if(someCondition){
// add dependency
}
}
Thanks in advance!!
testImplementation – required to compile tests. testCompileOnly – required only at test compile time.
Gradle is based on developing domain-specific language projects. Maven is based on developing pure Java language-based software. It uses a Groovy-based Domain-specific language(DSL) for creating project structure. It uses Extensible Markup Language(XML) for creating project structure.
The Gradle build system in Android Studio makes it easy to include external binaries or other library modules to your build as dependencies. The dependencies can be located on your machine or in a remote repository, and any transitive dependencies they declare are automatically included as well.
Gradle has built-in support for dependency management and lives up to the task of fulfilling typical scenarios encountered in modern software projects.
I found a solution for this:
Step1: Declare a boolean variable
in gradle at root level.
like: def someDependencyEnabled = true //This could be dynamically set.
Step2: Using this boolean
variable we can apply a check like:
if(someDependencyEnabled){
//Add some dependency
}
else
{
//Add some other dependency
}
Step3: Define Different source set for different situations:
android.sourceSets {
main {
java.srcDirs = ['src/main/java', someDependencyEnabled ? 'src/dependency_enabled_src' : 'src/dependency_disabled_src']
}
}
where: 'src/main/java' : is the common src file which contain common code.
'src/dependency_enabled_src': is the source folder that contain dependency specific code. which is further used by 'src/main/java'.
'src/dependency_disabled_src': is the source folder that contain alternate code when particular dependency is disabled.
In my case I wrote same name classes, methods & package name in both folders (dependency_enabled & dependency_disabled src) and wrote methods with desired implementation in dependency_enabled_src & empty methods for dependency_disabled_src.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With