Java apk上传自动识别包名版本信息
解析apk方法
1、apktool cmd解析
2、解压apk,读取AndroidManifest.xml获取版本信息
因为第一种太麻烦了,要部署到docker麻烦,选用了第二种
本示例是上传时,把APK解压,遍历文件,如果是AndroidManifest.xml文件就取里面的值
参考这这里,源码和jar可以从这里下载
https://chensl.iteye.com/blog/2174290
public String savePackage(CommonsMultipartFile file, Long pkVersion) throws Exception { if (file == null) { throw new RuntimeException("上传的文件为空,请重新上传!"); } byte[] uploadBytes = file.getBytes(); // 获取包信息apk信息的返回结果 String[] apkResult = new String[3]; ZipInputStream zs = new ZipInputStream(file.getInputStream()); BufferedInputStream bs = new BufferedInputStream(zs); ZipEntry zipEntry; while ((zipEntry = zs.getNextEntry()) != null) { if (zipEntry.isDirectory()) { continue; } byte[] bytes = null; if ("androidmanifest.xml".equals(zipEntry.getName().toLowerCase())) { bytes = new byte[(int) zipEntry.getSize()]; bs.read(bytes, 0, (int) zipEntry.getSize()); InputStream byteArrayInputStream = new ByteArrayInputStream(bytes); apkResult = AXMLPrinter.getApkInfo(byteArrayInputStream); } } bs.close(); zs.close(); if (StringUtils.isBlank(apkResult[0])) { throw new RuntimeException("未获取包名,请检测包"); } //end包 //get包名 String pkPackage=apkResult[0]; String fileName = file.getOriginalFilename(); String fileSuffix = fileName.substring(fileName.lastIndexOf(".") + 1, fileName.length()); PackageVer fileInfoModel = new PackageVer(); fileInfoModel.setPkName(fileName); fileInfoModel.setPkSize(file.getSize()); fileInfoModel.setPkVersion(pkVersion); fileInfoModel.setPkPackage(pkPackage); MessageDigest md5 = MessageDigest.getInstance("MD5"); byte[] digest = md5.digest(uploadBytes); String hashString = new BigInteger(1, digest).toString(16); fileInfoModel.setPkMd5(hashString); String fileId = fastDfsService.uploadPicFile(uploadBytes, fileSuffix); logger.info("uploadPicFile result={}", fileId); fileInfoModel.setPkUrl(fileUrlPrefix + "/" + fileId); fileInfoModel.setFileid(fileId); packageVerBiz.add(fileInfoModel); return "SUCCESS"; }
public static String[] getApkInfo(InputStream fileInputStream) throws Exception { final String[] apkResult = new String[3]; AXmlResourceParser parser = new AXmlResourceParser(); parser.open(fileInputStream); while (true) { int type = parser.next(); if (type == XmlPullParser.END_DOCUMENT) { break; } switch (type) { case XmlPullParser.START_TAG: { for (int i = 0; i != parser.getAttributeCount(); ++i) { if ("package".equals(parser.getAttributeName(i))) { apkResult[0] = getAttributeValue(parser, i); } else if ("versionCode".equals(parser.getAttributeName(i))) { apkResult[1] = getAttributeValue(parser, i); } else if ("versionName".equals(parser.getAttributeName(i))) { apkResult[2] = getAttributeValue(parser, i); } } break; } default: } } return apkResult; }