task signApkAndMeituanChannel() {
group = "channel"
description = "签名apk 并生成渠道包"
doLast {
File apkFile = null
def path = "${projectDir.absolutePath}/channel/v${VERSION_CODE}"
fileTree(path).each {
def fileName = it.getName()
if (it.isFile() && fileName.endsWith(".apk") && fileName.contains("_jiagu") && !fileName.contains("_sign")) {
// 找到未签名的apk文件
apkFile = it
}
}
if (apkFile == null || !apkFile.exists()) {
throw new FileNotFoundException('apkFile is not exists')
}
apkFile = zipAlignApk(apkFile)
apkFile = signApkV2(apkFile)
exec {
executable = 'java'
args = ['-jar', "${rootProject.getProjectDir()}/walle-cli-all.jar",
'batch', '-f',
"${project.getProjectDir()}/channel.txt",
apkFile.absolutePath
]
}
}
}
/**
* 加固后的apk 对齐压缩
* @param apk 已加固apk
* @return 返回对齐压缩后的apk
*/
def zipAlignApk(File apk) {
if (apk == null || !apk.exists()) {
println "---zipalign reinforceApk throw exception and forced stop!---"
throw new FileNotFoundException('apk is not exists and cannot reinforce')
}
def file = new File("${apk.absolutePath.replace(".apk", "_zip.apk")}")
if (file.exists()) {
file.delete()
}
exec {
commandLine "cmd", "/c", "${getApkSignerAndZipAlignPath()}/zipalign -v -p 4 ${apk.absolutePath} ${file.absolutePath}"
}
if (apk.exists()) {
apk.delete()
}
return file
}
/**
* 对apk签名
* @param zipApk 压缩对齐后的apk
* @return 签名后的apk
*/
def signApkV2(File apkFile) {
if (apkFile == null || !apkFile.exists()) {
println "---sign apkFile throw exception and forced stop!---"
throw new FileNotFoundException('apk is not exists and cannot reinforce')
}
def file = new File("${apkFile.absolutePath.replace("_zip.apk", "_sign.apk")}")
if (file.exists()) {
file.delete()
}
def storeFile = rootProject.file("keystore.jks")
def keyAlias = rootProject.ext.signing["keyAlias"]
def keyPassword = rootProject.ext.signing["keyPassword"]
def storePassword = rootProject.ext.signing["storePassword"]
exec {
commandLine "powershell", "/c", "${getApkSignerAndZipAlignPath()}/apksigner sign --ks ${storeFile.absolutePath} --ks-key-alias ${keyAlias} --ks-pass pass:${storePassword} --key-pass pass:${keyPassword} --out ${file.absolutePath} ${apkFile.absolutePath}"
}
if (apkFile.exists()) {
apkFile.delete()
}
def signBeforeFile = new File("${file.absolutePath}.idsig")
if (signBeforeFile.exists()) {
signBeforeFile.delete()
}
return file
}
/***
* 获取 SDK 目录下的最新 SDK 版本路径
* @return
*/
def getApkSignerAndZipAlignPath() {
def sdkDirectory = new File("${parseLocalProperties()}\\build-tools")
def listFiles = sdkDirectory.listFiles()
def fileSize = listFiles.size()
return listFiles[fileSize - 1]
}
/***
* 获取 SDK 路径
* @return
*/
def parseLocalProperties() {
File file = rootProject.file("local.properties")
if (file.exists()) {
InputStream inputStream = file.newDataInputStream()
Properties properties = new Properties()
properties.load(inputStream)
return properties.getProperty("sdk.dir")
}
throw new FileNotFoundException('local.properties is not exists and cannot reinforce')
}
网友评论