- 场景:
多渠道打包、版本共存、区分线上线下版本
- 假设项目分正式环境和测试环境两个版本,两个版本需要同时安装在一个手机上,此时需要两个applicationId
com.tikeyc.online
和com.tikeyc.offline
defaultConfig {
applicationId "com.tikeyc.online" // 正式
// applicationId "com.tikeyc.offline" // 测试
}
- 添加环境标记,在打包时指定线上线下环境
buildTypes {
release {
buildConfigField("boolean", "online", "${defaultConfig.applicationId == "com.tikeyc.online"}")
}
debug {
buildConfigField("boolean", "online", "${defaultConfig.applicationId == "com.tikeyc.online"}")
}
}
编译后在BuildConfig.class中会自动生成online
public final class BuildConfig {
public static final boolean DEBUG = Boolean.parseBoolean("true");
public static final String APPLICATION_ID = "com.tikeyc.online";
public static final String BUILD_TYPE = "debug";
public static final int VERSION_CODE = 1;
public static final String VERSION_NAME = "1";
// Field from build type: debug
public static final boolean online = true;
}
在JAVA业务代码中使用
public class MyContactsURL {
public static final String host = BuildConfig.online ? "online .xxx.xx" : "offline.xxx.xx";
}
- 指定线上、线下版本的applicationId和签名文件
defaultConfig {
applicationId "com.tikeyc.online" // 正式
// applicationId "com.tikeyc.offline" // 测试
}
signingConfigs {
def online = defaultConfig.applicationId == "com.tikeyc.online"
def file = online ? file("./online.jks") : file("./offline.jks")
def alias = online ? "online" : "offline"
release {
storeFile file
storePassword "online.123"
keyAlias alias
keyPassword "online.123"
}
debug {
storeFile file
storePassword "offline.123"
keyAlias alias
keyPassword "offline.123"
}
}
buildTypes {
release {
buildConfigField("boolean", "online", "${defaultConfig.applicationId == "com.tikeyc.online"}")
signingConfig signingConfigs.release
buildConfigField "boolean", "LOG_DEBUG", "false" //不显示log
minifyEnabled false // 打包是否代码混淆
shrinkResources false // 是否打开资源压缩
proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
}
debug {
buildConfigField("boolean", "online", "${defaultConfig.applicationId == "com.tikeyc.online"}")
signingConfig signingConfigs.debug
}
}
- 自动化配置
AndroidManifest.xml
文件中的值
比如配置百度地图的API_KEY
<meta-data
android:name="com.baidu.lbsapi.API_KEY"
android:value="${BAIDUMAP_KEY}" />
在build.gradle
文件中设置manifestPlaceholders
defaultConfig {
applicationId "com.tikeyc.online" // 正式
// applicationId "com.tikeyc.offline" // 测试
if (applicationId == "com.tikeyc.online") {
manifestPlaceholders = [
BAIDUMAP_KEY: "xxxxxxxxxxxxxxxxxxxxxxxxxxxxx",
]
} else {
manifestPlaceholders = [
BAIDUMAP_KEY: "xxxxxxxxxxxxxxxxxxxxxxxxxxxxx",
]
}
}
- 配置打包后的
apk
名称
android.applicationVariants.all {
variant ->
variant.outputs.all {
// 在这里修改apk文件名
// outputFileName = "tikeyc.apk"
def suffix = variant.applicationId == "com.tikeyc.online" ? "online" : "offline"
outputFileName = "tikeyc-${suffix}.apk"
}
}
网友评论