概述
最新项目出现了包体积上涨很多的问题,但是确不知到底是哪次提交导致的,为了避免后续再出现这种情况,利用gradle写了个包体积监控的任务。
流程
钉钉通知格式
实现
import org.apache.http.HttpResponse
import org.apache.http.HttpStatus
import org.apache.http.client.HttpClient
import org.apache.http.client.methods.HttpPost
import org.apache.http.entity.StringEntity
import org.apache.http.impl.client.HttpClients
import org.apache.http.util.EntityUtils
import java.text.SimpleDateFormat
def taskName = gradle.startParameter.taskNames[0]
def apkOutContext
android {
applicationVariants.all {
String variant = it.buildType.name
String buildName = ""
it.productFlavors.each { product ->
buildName = product.name
}
if (variant == "release" || variant == "Release") {
it.outputs.each {
if("assembleRelease" == taskName) {
apkOutContext = it
}
}
}
}
}
buildscript {
dependencies {
classpath fileTree(include: ['*.jar'], dir: new File(project.rootDir, "libs"))
}
}
gradle.buildFinished {
if (apkOutContext == null) {
return
}
def apkFile = apkOutContext.outputFile
def branchName = getGitBranch()
def date = getToday()
def versionName = android.defaultConfig.versionName
StringBuilder message = new StringBuilder()
message.append("\r\n")
.append("打包人:").append(getUserName())
.append("\r\n")
.append("项目:").append("满帮专车")
.append("\r\n")
.append("版本号:").append(versionName)
.append("\r\n")
.append("分支:").append(branchName)
.append("\r\n")
.append("大小:").append(getApkFileSize(apkFile))
.append("\r\n")
.append("生成时间:").append(date)
DingDing.send(message.toString())
}
static def getApkFileSize(apkFile) {
return (apkFile.length() / 1024) + "k"
}
static def getGitBranch() {
return 'git symbolic-ref --short -q HEAD'.execute().text.trim()
}
static def getUserName() {
return 'git config user.name'.execute().text.trim()
}
static def getToday() {
String str
SimpleDateFormat sdf = new SimpleDateFormat("yyyy.MM.dd/HH:mm:ss")
Calendar lastDate = Calendar.getInstance()
str = sdf.format(lastDate.getTime())
return str
}
class DingDing {
public static final String WEBHOOK_TOKEN = "https://oapi.dingtalk.com/robot/send?access_token=XXX"
static void send(String message) {
try {
sendMessageImp("打包信息", message)
} catch (Exception e) {
e.printStackTrace()
}
}
private static void sendMessageImp(String title, String message) throws Exception {
HttpClient httpclient = HttpClients.createDefault()
HttpPost httppost = new HttpPost(WEBHOOK_TOKEN)
httppost.addHeader("Content-Type", "application/json; charset=utf-8")
String textMsg = "{ \"msgtype\": \"text\", \"text\": {\"content\": \"" + title + ":" + message + "\"}}"
StringEntity se = new StringEntity(textMsg, "utf-8")
httppost.setEntity(se)
HttpResponse response = httpclient.execute(httppost)
if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
String result = EntityUtils.toString(response.getEntity(), "utf-8")
System.out.println(result)
}
}
}
依赖两个附件: