“This is the first day of my participation in the First Challenge 2022. For details: First Challenge 2022.”
background
In the process of multi-module project development, we will encounter such a scenario that the project relies on one of its own or another colleague’s AAR module. Sometimes, for the convenience of development and debugging, we often change AAR to local source code dependency. When the development is completed and submitted, we will modify back to AAR dependency, which will be very inconvenient. The development process is shown as follows:
To solve
At the beginning, we judged by dependency in app build.gradle that if the AAR needs local dependency, we replaced it with implementation Project dependency, and the pseudo-code is as follows:
dependencies {
if(enableLocalModule) {
implementation 'the custom: test: 0.0.1'
} else {
implementation project(path: ':test')}}Copy the code
This solves the problem, but if other modules also rely on the AAR module, the problem will arise. You can continue to modify the dependencies in other modules, but this will be intrusive and not completely resolved, and there will still be the possibility of inconsistencies between the local dependencies and the AAR dependencies.
Gradle officials provide a better way to resolve this scenario – DependencySubstitution:
Step 1: In settting.gradle, add the following code:
// Load the local module
if (file("local.properties").exists()) {
def properties = new Properties()
def inputStream = file("local.properties").newDataInputStream()
properties.load( inputStream )
def moduleName = properties.getProperty("moduleName")
def modulePath = properties.getProperty("modulePath")
if(moduleName ! =null&& modulePath ! =null) {
include moduleName
project(moduleName).projectDir = file(modulePath)
}
}
Copy the code
Step 2: Add the following code to your app’s build.gradle
configurations.all {
resolutionStrategy.dependencySubstitution.all { DependencySubstitution dependency ->
// use local module
if (dependency.requested instanceof ModuleComponentSelector && dependency.requested.group == "custom") {
def targetProject = findProject(":test")
if(targetProject ! =null) {
dependency.useTarget targetProject
}
}
}
}
Copy the code
Step 3: : in local.properties
moduleName=:test modulePath=.. /AndroidStudioProjects/TestProject/testModuleCopy the code
The aar module’s local dependencies can be debuggable by simply turning them on and off in local.properties, and the submission code does not need to be manually modified back to aar dependencies.
reference
- Customizing resolution of a dependency directly