You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何根据构建环境变体配置Android依赖库版本?

Android Gradle按构建变体指定依赖版本的实现方法

你的写法无法工作主要有两个问题:

  1. 错误地将applicationVariants的遍历放在buildTypes块内部,位置不符合Gradle的配置逻辑;
  2. dependencies块在Gradle配置阶段就会执行,这时候变体还未完成初始化,直接引用$version拿不到对应变体的版本值。

下面给两种可行的实现方案:

方案一:遍历所有变体动态添加依赖

如果你的Eval、Integration是通过buildType或productFlavor组合生成的变体,这种方法更灵活:

android {
    // 先定义对应的buildType(如果是用productFlavor同理)
    buildTypes {
        Eval {}
        Integration {}
        release {}
    }
}

// 遍历所有应用变体,为每个变体指定对应版本的依赖
applicationVariants.all { variant ->
    def targetVersion = '1.0.8' // 默认版本
    switch (variant.name) {
        case 'Eval':
            targetVersion = '1.0.6'
            break
        case 'Integration':
            targetVersion = '1.0.7'
            break
    }
    // 给当前变体的implementation配置添加依赖
    variant.dependencies.add('implementation', "com.example.example:test:$targetVersion")
}

// 其他通用依赖可以放在这里
dependencies {
    // 比如 implementation 'androidx.core:core-ktx:1.12.0'
}

方案二:直接在buildType中配置依赖

如果Eval、Integration本身就是独立的buildType,这种写法更简洁直观:

android {
    buildTypes {
        Eval {
            // 为Eval构建类型指定专属依赖版本
            dependencies {
                implementation "com.example.example:test:1.0.6"
            }
        }
        Integration {
            dependencies {
                implementation "com.example.example:test:1.0.7"
            }
        }
        release {
            dependencies {
                implementation "com.example.example:test:1.0.8"
            }
        }
    }
}

// 通用依赖统一放在这里
dependencies {
    // 其他不区分变体的依赖
}

注意点

  • 变体名称区分大小写,确保variant.name和你实际的变体名称完全一致;
  • 如果是productFlavor和buildType的组合变体(比如EvalDebug),可以通过variant.flavorName或variant.buildType.name来判断,进一步细化版本规则。

内容的提问来源于stack exchange,提问作者Dev Loots

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.28 08:10:09