// 以下为打渠道包方法和任务
ArrayList<String> getChannelList() {
ArrayList<String> list = new ArrayList<String>()
def path = rootProject.projectDir.absolutePath + '/channel/channel.txt'
file(path).eachLine { channel ->
list.add(channel)
}
return list
}
// 往META-INF里添加空白文件
task doChannelPkg() << {
def name = rootProject.hasProperty("APK_NAME") ? APK_NAME : ""
if (name == null || "".equals(name)) {
throw new RuntimeException("doChannelPkg name should not be null")
}
def dir = rootProject.projectDir.absolutePath + '/app/build/outputs/apk/prod/release'
getChannelList().each { channel ->
def destName = "${name.replace(".apk", "")}_${channel}.apk"
copy {
from "${dir}/${name}"
into dir
rename {
destName
}
}
def channelDir = "${dir}/${channel}"
file(channelDir).mkdir()
file("${channelDir}/META-INF").mkdir()
file("${channelDir}/META-INF/channel_${channel}").createNewFile()
ant.zip(basedir: channelDir, includes: "META-INF/channel_${channel}", keepcompression: true, update: true,
destfile: "${dir}/${destName}")
file(channelDir).deleteDir()
}
}
// Mac上打包没通过,待查原因
task doChannelRePkg() << {
def name = rootProject.hasProperty("APK_NAME") ? APK_NAME : ""
if (name == null || "".equals(name)) {
throw new RuntimeException("doChannelPkg name should not be null")
}
def rootDir = rootProject.projectDir.absolutePath
def dir = rootDir + '/app/build/outputs/apk/dev/debug'
def apktoolJar = 'apktool_2.3.3.jar'
def apktool = rootDir + "/channel/${apktoolJar}"
copy {
from apktool
into dir
}
getChannelList().each { channel ->
def destName = "${name.replace(".apk", "")}_${channel}.apk"
copy {
from "${dir}/${name}"
into dir
rename {
destName
}
}
def channelDir = "${dir}/${channel}"
file(channelDir).mkdir()
file("${channelDir}/assets").mkdir()
def channelFile = file("${channelDir}/assets/channel")
if (!channelFile.exists()) {
channelFile.createNewFile()
}
def bw = new BufferedWriter(new FileWriter(channelFile))
bw.write("${channel}")
bw.close()
// 解压缩
exec {
workingDir dir
commandLine 'java', '-jar', apktoolJar, 'd', '-f', destName, '-o', "${channel}/base-apk"
}
// 写入渠道号
copy {
from channelFile
into "${dir}/${channel}/base-apk/assets"
}
// 打包
exec {
workingDir dir
commandLine 'java', '-jar', apktooJar, 'b', "${channel}/base-apk", '-o',
"${destName.replace(".apk", "")}-unsigned.apk"
}
// 签名
def keyStore = rootProject.projectDir.absolutePath + '/app/key_store'
copy {
from keyStore
into dir
rename {
'key_store'
}
}
def storePass = 'xxx'
def alias = 'xxx'
def keyPass = 'xxx'
exec {
workingDir dir
commandLine 'jarsigner',
'-sigalg', 'MD5withRSA',
'-digestalg', 'SHA1',
'-keystore', 'key_store',
'-storepass', storePass,
'-keypass', keyPass,
'-signedjar', "${destName.replace(".apk", "")}_signed.apk",
destName, alias
}
file(channelDir).deleteDir()
}
}
ApkTooll 链接:https://ibotpeaches.github.io/Apktool/