软件编程
位置:首页>> 软件编程>> Android编程>> Android Gradle模块依赖替换使用技巧

Android Gradle模块依赖替换使用技巧

作者:汪海游龙  发布时间:2021-07-03 20:22:53 

标签:Android,Gradle,模块,依赖替换

背景

我们在多模块项目开发过程中,会遇到这样的场景,工程里依赖了一个自己的或者其他同事的 aar 模块,有时候为了开发调试方便,经常会把 aar 改为本地源码依赖,开发完毕并提交的时候,会再修改回 aar 依赖,这样就会很不方便,开发流程图示如下:

Android Gradle模块依赖替换使用技巧

解决

一开始我们通过在 appbuild.gradle 里的 dependency 判断如果是需要本地依赖的 aar,就替换为 implementation project 依赖,伪代码如下:

dependencies {
   if(enableLocalModule) {
       implementation 'custom:test:0.0.1'
   } else {
       implementation project(path: ':test')
   }
}

这样就可以不用每次提交代码还要修改回 aar 依赖,但是如果其他模块如果也依赖了该 aar 模块,就会出现问题,虽然可以继续修改其他模块里的依赖方式,但是这样就会有侵入性,而且不能彻底解决问题,仍然有可能出现本地依赖和 aar 依赖的代码不一致问题。

Gradle 官方针对这种场景提供了更好的解决方式 DependencySubstitution,使用方式如下:

步骤1:

settting.gradle,添加如下代码:

// 加载本地 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)
   }
}

步骤2:

appbuild.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
           }
       }
   }
}

步骤3:

local.properties

moduleName=:test
modulePath=../AndroidStudioProjects/TestProject/testModule

到这里就大功告成了,后续只需要在 local.properties 里开启和关闭,即可实现 aar 模块本地依赖调试,提交代码也不用去手动修改回 aar 依赖。

来源:https://juejin.cn/post/7062642189154648101

0
投稿

猜你喜欢

手机版 软件编程 asp之家 www.aspxhome.com