概述
我们在开发过程中,会经常遇到,同样的业务逻辑,需要配置不同的资源的情况。有时是不同的渠道,有时是不同的语言环境,各种不同。
如果我们在业务逻辑中,去实现这些差异化,会导致两个问题:
- 代码量很大,分支路径很多。而很多路径在实际使用中是用不到的,造成代码质量差。
- 用业务逻辑去区分情况加载资源,会导致包内需要包含大量的资源,造成包体积过大。
所以,我们需要在编译阶段,就区分种种情况,给予相应的资源。
Android中build.gradle
的productFlavors为我们提供了这样的能力。
快速使用
在module的build.gradle中,我们通过flavorDimensions和productFlavors的配合,来实现多维度的区分:
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" } } ... }