风味维度
使用flavorDimensions定义风味维度,维度越多,能打出的渠道包越丰富。
单风味维度
defaultConfig {
flavorDimensions "default"
}
productFlavors {
google {
}
huawei {
applicationIdSuffix ".huawei"
}
}
单风味维度只能构建productFlavors 里定义的风味维度,不能组合. 如图只能构建google和huawei两种渠道包
1.jpg
多维风味维度
defaultConfig {
flavorDimensions "company","channel"
}
productFlavors {
companyA {
dimension "company"
}
companyB {
dimension "company"
}
channelA {
dimension "channel"
}
channelB {
dimension "channel"
}
}
根据company和channel进行组合, 上述可以构建companyAchannelA , companyAchannelB, companyBchannelA , companyBchannelB 四种组合的渠道包
2.jpegBuildConfig
给BuildConfig生成属性
buildConfigField "boolean", "LOG_DEBUG", "false"
//动态赋值url和端口
buildConfigField('String', 'BASE_URL', '"https://www.baidu.com/"')
buildConfigField('int', 'URL_PORT', '5672')
通过BuildConfig 判断当前flavor
3.jpeg通过Flavor应用插件
项目中可以有类似需求, google渠道应用'com.google.gms.google-services'插件, 而huawei渠道应用'com.huawei.agconnect'插件
可以通过判断Flavor应用对应渠道插件,代码如下
def String getCurrentFlavor() {
Gradle gradle = getGradle()
String tskReqStr = gradle.getStartParameter().getTaskRequests().toString()
Pattern pattern;
if (tskReqStr.contains("assemble"))
pattern = Pattern.compile("assemble(\w+)(Release|Debug)")
else
pattern = Pattern.compile("bundle(\w+)(Release|Debug)")
Matcher matcher = pattern.matcher(tskReqStr)
if (matcher.find()) {
return matcher.group(1).toLowerCase()
} else {
return "";
}
}
gradle.projectsEvaluated {
preBuild.dependsOn(applyPluginByFlavor)
}
// Then check on the parameter, which comes from the command line
task applyPluginByFlavor {
def flavorType = ""
flavorType = getCurrentFlavor();
if (flavorType.equals("google")) {
println("正在构建 google 包")
apply plugin: 'com.google.gms.google-services'
apply plugin: 'com.google.firebase.crashlytics'
apply plugin: 'com.google.firebase.firebase-perf'
}
if (flavorType.equals("huawei")) {
println("正在构建 huawei 包")
apply plugin: 'com.huawei.agconnect'
apply plugin: 'com.huawei.agconnect.apms'
}
}
获取 MetaData 属性
// manifest占位符
manifestPlaceholders = [
HW_BANNER_ID : "xxx"
]
// manifest 中配置meta-data
<meta-data
android:name="HW_BANNER_ID"
android:value="${HW_BANNER_ID}" />
获取在gradle中配置的HW_BANNER_ID
public String getMetaData(String key) {
try {
PackageManager packageManager = getPackageManager();
ApplicationInfo applicationInfo = packageManager.getApplicationInfo(this
.getPackageName(), PackageManager.GET_META_DATA);
return applicationInfo.metaData.getString(key);
} catch (Exception e) {
e.printStackTrace();
}
return "";
}
网友评论