Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Android studio | Dependency Management

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!!

like image 856
Ashlesha Sharma Avatar asked Feb 16 '18 09:02

Ashlesha Sharma


People also ask

What is difference between Testcompile and testImplementation?

testImplementation – required to compile tests. testCompileOnly – required only at test compile time.

What is Gradle vs Maven?

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.

What is Gradle and dependency in Android Studio?

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.

Is Gradle a dependency manager?

Gradle has built-in support for dependency management and lives up to the task of fulfilling typical scenarios encountered in modern software projects.


1 Answers

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.

like image 135
Ashlesha Sharma Avatar answered Sep 30 '22 17:09

Ashlesha Sharma