ProductFlavors 简单使用

节选自:ProductFlavors 简单使用


概述

我们在开发过程中,会经常遇到,同样的业务逻辑,需要配置不同的资源的情况。有时是不同的渠道,有时是不同的语言环境,各种不同。

如果我们在业务逻辑中,去实现这些差异化,会导致两个问题:

  1. 代码量很大,分支路径很多。而很多路径在实际使用中是用不到的,造成代码质量差。
  2. 用业务逻辑去区分情况加载资源,会导致包内需要包含大量的资源,造成包体积过大。

所以,我们需要在编译阶段,就区分种种情况,给予相应的资源。

Android中build.gradleproductFlavors为我们提供了这样的能力。

快速使用

在module的build.gradle中,我们通过flavorDimensionsproductFlavors的配合,来实现多维度的区分:

android {
    compileSdkVersion 27
    defaultConfig {
        applicationId "com.example.oceanlong.buildtestpro"
        minSdkVersion 21
        targetSdkVersion 27
        versionCode 1
        versionName "1.0"
        testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
    }

    ...

    flavorDimensions "country" 

    productFlavors {
        china {
            applicationId "com.example.oceanlong.buildtestfree"
            dimension "country"
        }
        usa {
            applicationId "com.example.oceanlong.buildtestpro"
            dimension "country"
        }
    }
    ...
}

发表评论