Gradle 之多环境构建(开发环境,线上环境)

  1. 在build.gradle 内添加以下配置:
android {
      ...
    flavorDimensions "default"
    productFlavors {
        //测试站和正式站
        //构建时命令:gradlew assembleOnline  / gradlew assembleDev
        online {
            dimension "default"
            //可以构建不同的包名
            applicationId "com.xxx.xxx"
            resValue "string", "app_name", "xxx"
            buildConfigField "String", "HOST_URL", "\"https://online.xxx.com/\""
            buildConfigField "String", "SECRET", "\"xxxxxxxxxxxxxxx\""
            buildConfigField "String", "APP_ID", "\"xxx\""
            buildConfigField "int", "SOCKET_PORT", "8092"
        }

        dev {
            dimension "default"
            applicationId "com.xxx.xxx"
            resValue "string", "app_name", "xxx-测试站"
            buildConfigField "String", "HOST_URL", "\"https://tester.xxx.com/\""
            buildConfigField "String", "SECRET", "\"xxxxxxxxxxxxxxxxxxxx\""
            buildConfigField "String", "APP_ID", "\"xxx\""
            buildConfigField "int", "SOCKET_PORT", "8093"
        }

    }
}

点击build,可以生成BuildConfig.java文件,gradle定义的变量都会已静态常量的形式展示:

public final class BuildConfig {
  public static final boolean DEBUG = Boolean.parseBoolean("true");
  public static final String APPLICATION_ID = "com.xxx.xxx";
  public static final String BUILD_TYPE = "debug";
  public static final String FLAVOR = "dev";
  public static final int VERSION_CODE = 86;
  public static final String VERSION_NAME = "2.6";
  // Field from product flavor: dev
  public static final String APP_ID = "xxx";
  // Field from product flavor: dev
  public static final String HOST_URL = "https://tester.xxxx.com/";
  // Field from product flavor: dev
  public static final String SECRET = "xxxxxxxxxxxxxxxxxxx";
  // Field from product flavor: dev
  public static final int SOCKET_PORT = 8093;
}

在使用的时候,比如要使用HOST_URL,可以直接使用BuildConfig.HOST_URL

在Build Variants中会生成四种构建类型


image.png

开发时具体使用:
如果需要开发环境,Build Variants选择devDebug,连接手机进行调试。
如果需要调试线上环境,选择onlineDebug

打包:
可以使用命令:
gradlew assembleOnline 可生成线上包。
gradlew assembleDev 可生成测试站的正式包

也可以使用Android Studio右侧的Gradle

如果升级Android Studio后,右侧Gradle没有assemble相关的选项


image.png

出现该问题,是因为升级了android studio到4.2.1,默认关闭了,打开即可


image.png

打开后,重新refresh一下:
image.png

就可以打包了。

参考:

  1. android studio的右侧gradle只有dependens,没有tasks任务栏
    https://blog.csdn.net/feijian_/article/details/117573009
  2. Android Studio3.0 flavorDimensions多维度理解(版本差异化打包)
    https://blog.csdn.net/chen_xi_hao/article/details/80526049
  3. Gradle 之创建 Build Variants
    https://www.jianshu.com/p/6ceb15559e81

你可能感兴趣的:(Gradle 之多环境构建(开发环境,线上环境))