需求场景:公司开发的线上打包系统需要获取apk的versionCode值进行显示并修改,减少每次都手动查看apk的versioncode的繁琐步骤,通过集成jar包,代码实现,以达成自动化,方便获取。
实现原理:通过aapt命令行获取apk的信息,再进行逻辑判断处理,获取到versioncode值;
aapt dump badging demo.apk
代码实现步骤:
1、声明命令行类
public class AaptTool {
//aapt命名行查看apk信息
public static String genApkInfoCommand(String apkPath){
String format="aapt dump badging %s";
return String.format(format,apkPath);
}
//生成versioncode文件,以便工具组获取显示
public static String genVersionCodeText(String versionCode,String VersionCodeTextPath){
String format="echo %s > %s";
return String.format(format,versionCode,VersionCodeTextPath);
}
}
2、声明main类入口,进行代码逻辑判断获取versioncode
public class GetVersionCode {
// static String apkpath="/Users/DexLin/Downloads/xls/release.apk";
// static String versionCodeTextPath="/Users/DexLin/Downloads/xls/";
static String apkpath;//读取apk的路径
static String versionCodeTextPath;//输出versioncode文件路径
public static void main(String[] args) {
apkpath=args[0];
versionCodeTextPath=args[1];
//执行aapt命令
execute(AaptTool.genApkInfoCommand(apkpath));
}
public static int execute(String command) {
String[] cmd = {"/bin/bash"};
Runtime rt = Runtime.getRuntime();
Process proc = null;
try {
proc = rt.exec(cmd);
} catch (IOException e) {
e.printStackTrace();
}
OutputStream os = proc.getOutputStream();
BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(os));
try {
bw.write(command);
bw.flush();
bw.close();
readConsole(proc);
proc.waitFor();//等待命令执行完毕
} catch (Exception e) {
e.printStackTrace();
}
int retCode = proc.exitValue();
if (retCode != 0) {
readConsole(proc);
System.err.println("UnixScriptUil.execute 出错了!!");
}
return retCode;
}
/**
* 读取控制命令的输出结果
*/
public static String readConsole(Process process) {
StringBuffer cmdOut = new StringBuffer();
InputStream fis = process.getInputStream();
BufferedReader br = new BufferedReader(new InputStreamReader(fis));
String line = null;
try {
while ((line = br.readLine()) != null) {
cmdOut.append(line).append(System.getProperty("line.separator"));
if(line.contains("versionCode")){
//获取第一行:package: name='com.chbxf.lcq.yyjsqq' versionCode='16' versionName='1.16' platformBuildVersionName=''
String arr[]=line.split(" ");
for(String str:arr){
if(str.contains("versionCode")){
String versioncodeArr[]=str.split("=");
String versionCode=versioncodeArr[1].substring(1,versioncodeArr[1].length()-1);
execute(AaptTool.genVersionCodeText(versionCode,versionCodeTextPath+"/"+versionCode+".txt"));
System.out.println("值:"+versionCode);
}
}
}
}
} catch (IOException e) {
e.printStackTrace();
}
return cmdOut.toString().trim();
}
}
3、生成jar包,在AndroidStudio开发工具的build.gradle文件配置,通过gradle的命令行生成jar包
task makeVersionCodeJar(type: FatCapsule){
//类名
applicationClass 'com.appgame.tool.version.GetVersionCode'
//生成jar包的命名
baseName "versioncode_${signToolVersion}"
}
4、通过java命令行,写在shell脚本,工具组通过调用shell脚本进行实现versioncode获取显示即可
java -jar getversioncode.jar apkpath(apk路径) versioncodeTextPath(生成versioncd)