一、 在項(xiàng)目多渠道開發(fā)時,除了對不同的渠道除了做統(tǒng)計外,還可以對不同的渠道加載不同的代碼及資源,具體的部署可以參考 Android studio gradle中分渠道加載res、libraries及Class ;在模塊化拆分后,若恰好在模塊內(nèi)部的代碼及資源也要根據(jù)不同的渠道發(fā)布不同的aar包到nexus倉庫,該怎么配置呢?
二、思路:一般單獨(dú)拆分出的library基本都是將代碼及資源打包成aar包并上傳,為了使用方便,最好是在uploadArchives時就上傳到不同的artifact下。當(dāng)然也可以傳到不 的group下,但若在一個項(xiàng)目中有多個library時,只需要對其中的某個子庫(如core-ui分離下的ui庫)進(jìn)行上傳時最好上傳不同的artifact下,一般只需要在手動選擇Build Variants后就動態(tài)修改要上傳的POM_ARTIFACT_ID即可。
- 將POM_ARTIFACT_ID定義在library項(xiàng)目下的gradle.properties文件中,如:
POM_ARTIFACT_ID=account
2.若library開發(fā)的項(xiàng)目有用于測試的demo app,需要在app gradle下配置:
// 在dependencies下正常引入
implementation project(':account')
//需要與library庫創(chuàng)建對應(yīng)的productFlavors
android{
…
flavorDimensions "mode"
publishNonDefault true
productFlavors {
official {}
mi {}
}
}
//需要指定編譯配置
configurations {
officialDebug
miDebug
officialRelease
miRelease
}
3.在library的build.gradle文件中創(chuàng)建不同的變體,并在選擇不同的Build Variants后更新發(fā)布時使用的POM_ARTIFACT_ID:
// 在dependencies下正常引入
android{
flavorDimensions "mode"
productFlavors {
official {}
mi {}
}
// 取出當(dāng)前選擇的渠道名
def currentFlavor = getCurrentFlavor()
println "---> currentFlavor = $currentFlavor"
if ("mi".equalsIgnoreCase(currentFlavor)) {
// 取要指定默認(rèn)發(fā)布要使用的configuration
defaultPublishConfig “miRelease”
// 在取出渠道名判斷后更新POM_ARTIFACT_ID
replacePropertiesValue('POM_ARTIFACT_ID', 'account-mi')
} else {
defaultPublishConfig "officialRelease"
replacePropertiesValue('POM_ARTIFACT_ID', 'account')
}
}
// 取出當(dāng)前選擇的渠道名
def getCurrentFlavor() {
Gradle gradle = getGradle()
String taskStr = gradle.getStartParameter().getTaskRequests().toString()
println("taskStr:" + taskStr)
Pattern pattern
if (taskStr.contains("assemble")) {
pattern = Pattern.compile("assemble(\\w+)(Release|Debug)")
} else {
pattern = Pattern.compile("generate(\\w+)(Release|Debug)")
}
Matcher matcher = pattern.matcher(taskStr)
if (matcher.find()) {
return matcher.group(1)
}
return ""
}
// 替換library項(xiàng)目下的gradle.properties中的key-value值,key下value不同時才替換
def replacePropertiesValue(key, replaceValue) {
if (project.hasProperty(key)) {
def value = project.properties.get(key)
if (!replaceValue.equalsIgnoreCase(value)) {
ant.replace(file: "gradle.properties", token: "$key=$value", value: "$key=$replaceValue")
}
}
}
至此就能成功的將aar包發(fā)布到遠(yuǎn)程nuxus倉庫,若在demo工程里跑起來了。但在主項(xiàng)目里一樣需要判斷配置。
三、主項(xiàng)目工程配置
- 在主工程中配置的渠道需要包含library中包含的渠道:
productFlavors {
official {}
mi {}
Baidu{}
}
- 需要使用上面的currentFlavor()函數(shù)獲取當(dāng)前編譯的flavor再選擇依賴的庫:
dependencies{
def currentFlavor = getCurrentFlavor()
println "---> currentFlavor = $currentFlavor"
if ("mi".equalsIgnoreCase(currentFlavor)) {
// implementation mi版本庫
} else {
// implementation official版本庫
}
}