14

Android Gradle 技巧之一: Build Variant 相关

 4 years ago
source link: https://kvh.io/gradle-indepth-build-variant.html
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
neoserver,ios ssh client

android gradle 插件,允许对最终的包以多个维度进行组合。

BuildVariant = ProductFlavor x BuildType

两个维度

最常见的就是这样:

productFlavors {
    pro {
    }

    fre {
    }
}
lintOptions {
    abortOnError false
}

buildTypes {
    debug {
    }
    release {
    }
}

其中,buildTypes 一般都会有 debug 或者release,标示编译的类型,通常在混淆代码、可调式、资源压缩上做一些区分。

productFlavor 则为了满足“同一个project,根据一个很小的区分,来打不同的包”这个需求。

这两个维度的组合,会产生如下包:

  • proDebug
  • proRelease
  • freDebug
  • proRelease

更多的维度

flavorDimensions 'abi', 'version'

productFlavors {
    pro {
        dimension 'version'
    }

    fre {
        dimension 'version'
    }

    arm {
        dimension 'abi'
    }

    mips {
        dimension 'abi'
    }
}

buildTypes {
    debug {
    }
    release {
    }
}

productFlavor 本身定义了2个维度,记上 buildType,则有三个维度,会产生如下的包:

  • armProDebug
  • armProRelease
  • armFreDebug
  • armFreRelease
  • mipsProDebug
  • mipsProRelease
  • mipsFreDebug
  • mipsFreRelease

其中每个维度组合,都可以设置本身的 dependency、test source。下面做一个举例。

Flavor 与 Dependency

需求

module 中有若干个 flavors,例如:fre 和 pro,分别依赖不同的库,这些库有的是本地 jar 库,有的是远程库。

方案

nUJ77rY.jpg!web

遍历 Build Variant

需求

Bugtags 的 android sdk,有一个自动上传符号表功能, 在最初,是这样配置的:

apply plugin: 'com.bugtags.library.plugin'
bugtags {
    appKey "APP_KEY"
    appSecret  "APP_SECRET"
    mappingUploadEnabled false
}

后来,我们增加了一个 beta-live 的机制,用来区分测试和上线的 APP,这样,同一个 APP,就有两套 APP_KEY 和 APP_SECRET 了,很明显上方的配置方式就不在适用。

方案

android gradle 插件提供了 android.applicationVariants 索引来遍历所有的 build variant

后来,我们采取了一个方案,遍历 Build Variant,设置 extension 信息来兼容这种需求。

afterEvaluate {
    android.applicationVariants.each { variant ->
        def bugtagsAppKey = null;
        def bugtagsAppSecret = null;

        if (variant.name.contains("debug")) {
            bugtagsAppKey = 'APP_KEY_BETA'
            bugtagsAppSecret = 'APP_SECRET_BETA'
        } else if (variant.name.contains("release")) {
            bugtagsAppKey = 'APP_KEY_LIVE'
            bugtagsAppSecret = 'APP_SECRET_LIVE'
        }

        variant.ext.bugtagsAppKey = bugtagsAppKey
        variant.ext.bugtagsAppSecret = bugtagsAppSecret
    }
}

apply plugin: 'com.bugtags.library.plugin'

总结

本文主要是介绍了 build variant 的概念,还介绍了两个日常应用案例。希望对大家有帮助。

参考资料

android-build-tool

有问题?在文章下留言或者加 qq 群:453503476,希望能帮到你。

本文由kvh 创作,采用 CC BY 3.0 CN协议 进行许可。 可自由转载、引用,但需署名作者且注明文章出处。如转载至微信公众号,请在文末添加作者公众号二维码。

Mz6rIbQ.jpg!web

About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK