android多渠道編譯運行在真機上調試時,可以通過左下角的build Variates選擇渠道編譯
//在build.gradle的android節點下配置
// 多渠道打包
flavorDimensions 'channel'
productFlavors {
channel_1 {
resValue 'string', 'app_name', '渠道一'
resValue 'string', 'chanel_name', "channel_1"
buildConfigField('int', 'platform', '1')
buildConfigField('String', 'buglyId', '"bbd2bd7e01"')
}
channel_2 {
//打包更改包名
applicationIdSuffix '.channel'
resValue 'string', 'app_name', '渠道二'
resValue 'string', 'chanel_name', "channel_2"
buildConfigField('int', 'platform', '2')
buildConfigField('String', 'buglyId', '"bbd2bd7e02"')
}
}
// 更改打包名稱,正式打包時才需要
applicationVariants.all {
//判斷是release還是debug版本
def buildType = it.buildType.name
if (buildType == 'release') {
def fileName
//下面的channel是獲取渠道號,你獲取渠道號不一定會和我的代碼一樣,
// 因爲有可能你的渠道名稱的規則和我的不一樣,我的規則是${渠道名}-${applicationId},所以我是這樣取的。
//def channel = it.productFlavors[0].name
def channel = it.productFlavors[0].resValues.get('app_name').value
def chanel_name = it.productFlavors[0].resValues.get('chanel_name').value
//獲取當前時間的'YYYY-MM-dd'格式。
def createTime = new Date().format('yyyyMMddHHmm', TimeZone.getTimeZone('GMT+08:00'))
//只對Release包起作用,如果不是Release包則不變更輸出路徑,否則可能導致AS無法自動安裝debug包。
it.getPackageApplication().outputDirectory = new File(project.rootDir.absolutePath + "/app/release/${chanel_name}/apk-${createTime}")
it.outputs.each {
//只對Release包起作用,如果不是Release包則不變更名稱。
//我此處的命名規則是:渠道名-版本名-創建時間-構建類型.apk
fileName = "${channel}-V${defaultConfig.versionName}-${createTime}-${buildType}.apk"
//將名字打印出來,以便及時查看是否滿意。
println("文件名:-----------------${fileName}")
//重新對apk命名。(適用於Gradle4.0以下版本)
//it.outputFile = new File(it.outputFile.parent, fileName)
//重新對apk命名。(適用於Gradle4.0(含)以上版本)如果你Gradle版本是4.0以下版本則將上面的一行代碼放開並註釋下面的這一行。
it.outputFileName = fileName
}
}
}
compileOptions {
sourceCompatibility JavaVersion.VERSION_1_8
targetCompatibility JavaVersion.VERSION_1_8
}
//在main同級目錄下創建channel_1, channel_2文件夾,在其目錄下分別創建java和res文件用來放不同渠道java類和資源文件