使用Gradle构建多个不同applicationId包
2018-03-08 本文已影响46人
chenzhenlindx
开发环境
- AndroidStudio 3.0.1
- classpath 'com.android.tools.build:gradle:3.0.1'
- gradle-4.1-all.zip
背景
app首先在连接开发服务器开发,一定阶段提交给测试(连接测试服务器),测试通过后连接正式环境,提供给用户使用。
通常的做法,就是需要哪个地址,就修改API_URL 重新打包。
项目代码如下:
/**
* 正式环境
*/
public static final String API_URL = "http://120.202.24.118/";
/**
* 测试环境
*/
//public static final String API_URL = "http://172.29.1.18/";
/**
* 开发环境
*/
//public static final String API_URL = "http://172.29.1.20/";
Retrofit retrofit = new Retrofit.Builder()
.baseUrl(API_URL)
.client(new OkHttpClient())
.addConverterFactory(GsonConverterFactory.create())
.build();
需求
可是有一天,测试同事跑来说,每次测试不同版本只能安装一个app(applicationId是唯一的,会进行覆盖),他想在同一台手机上安装多个app,app之间的区别只是它们的后台服务接口地址API_URL不同,当然最好app的桌面名字能区分出来是哪个服务接口地址,这样测试就方便了,即:
- 生成不同的applicationId;
- 使用不同的服务地址API_URL;
- 使用不同的应用名称app_name。
解决方案
使用productFlavors,同时改变API_URL和app_name
1. strings的app_name
由于app_name是动态的所以肯定不能写死了,把它删掉
<!--
<string name="app_name">Test</string>
-->
2.设置build.gradle的productFlavors
//解决Error:All flavors must now belong to a named flavor dimension. Learn more at https://d.android.com
flavorDimensions "versionCode"
productFlavors {
dev {
applicationId "cn.czl.test"
flavorDimensions "versionCode"
buildConfigField 'String', 'API_URL', '"http://172.29.1.20/"'
resValue "string", "app_name", "APP开发"
}
product {
applicationId "cn.czl.test.product"
flavorDimensions "versionCode"
buildConfigField 'String', 'API_URL', '"http://172.29.1.18/"'
resValue "string", "app_name", "APP测试"
}
official {
applicationId "cn.czl.test.official"
flavorDimensions "versionCode"
buildConfigField 'String', 'API_URL', '"http://120.202.24.118/"'
resValue "string", "app_name", "APP正式"
}
}
上面我们分别设置三个版本各自的applicationId,API_URL,app_name
3.代码中引用动态API_URL
我们设置了不同版本的对应API_URL,代码肯定是要用它的,build完毕后。
直接可以用BuildConfig.API_URL,这个是动态的,不同版本会自动生成不同的值。
Retrofit retrofit = new Retrofit.Builder()
.baseUrl(BuildConfig.API_URL)
.client(new OkHttpClient())
.addConverterFactory(GsonConverterFactory.create())
.build();
4. 执行gradlew assembleDebug
执行命令后会生成

安装完成后,桌面会显示三个图标一样的app

他们功能完全一样,只是后台服务接口地址API_URL不一样。
这样就可以愉快的同时进行三个不同版本app测试同时互相比对数据的正确性了。
5. 指定生成apk名称
def releaseTime() {
return new Date().format("yyyy-MM-dd HHmmss", TimeZone.getDefault())
}
def applicationName(String applicationId) {
if ("com.zhhx.property.dev".equals(applicationId)) {
return "智慧物业开发"
} else if ("com.zhhx.property.product".equals(applicationId)) {
return "智慧物业测试"
}else if ("com.zhhx.property".equals(applicationId)) {
return "智慧物业"
}
}
applicationVariants.all { variant ->
variant.outputs.all { output ->
outputFileName = "${applicationName(variant.applicationId)}-" +
"${defaultConfig.versionName}-" +
"${variant.productFlavors[0].name}-" +
"${buildType.name}-" +
"${releaseTime()}.apk"
}
}
修改后,执行gradlew assembleDebug
,生成apk如下:
