使用apktool打包包体变大问题

项目中经常使用到apktool打包,有一次出游戏渠道包时发现原本的游戏包只有332M,令人诧异的是通过apktool打包后包体大小变成了429M,增加了将近100M,虽然有往游戏包中加资源,但肯定不可能增加100M。
最后想到是否是因为出来的渠道包没有压缩的关系,然后通过压缩工具解压包体后再压缩回去果然包体变小了,并且也能正常使用。
尴尬。。。总不能以后出包都要这样操作一遍吧。这问题还是需要解决,只能去详细了解一下apktool了。
将游戏包反编译之后,查看apktool.yml文件,能引起我注意的是doNotCompress,翻译过来不就是不压缩么,也就是以下类型是不压缩的?指定一个文件类型不压缩,那能不能指定具体文件不压缩呢?


apktool2.2.3

经过我测试,使用apktool2.0.2反编译之后doNotCompress是指定具体文件来不压缩的


apktool2.0.2

那是不是意味着我们降低apktool版本就能解决这个问题呢?如果运气好的话是能够解决的,但我的运气不好,遇到如下问题。
image.png

查看相关资料后得知,apktool在2.0.2这个版本之后将doNotCompress由原本指定具体文件到指定为文件类型,原因是在Windows下命令行支持的字符串长度是有限制的,在计算机上运行 Microsoft Windows XP 或更高版本,可以在命令提示符下使用的字符串的最大的长度 8191 个字符,也就是超过8191个个字符的命令会出现问题,很明显,我的命令肯定超过了。。。
所以还是使用新版本吧,有一个很简单的解决方案,那就是手动修改apktool.yml,将不需要压缩的文件去掉。可是我们的目的就是不要手动,那还是查看源码吧。

从程序主入口开始查看


image.png
public static void main(String[] args) throws IOException, InterruptedException, BrutException {
         //....................省略代码........................//
        // @todo use new ability of apache-commons-cli to check hasOption for non-prefixed items
        boolean cmdFound = false;
        for (String opt : commandLine.getArgs()) {
            if (opt.equalsIgnoreCase("d") || opt.equalsIgnoreCase("decode")) {
                cmdDecode(commandLine);
                cmdFound = true;
            } else if (opt.equalsIgnoreCase("b") || opt.equalsIgnoreCase("build")) {
                cmdBuild(commandLine);
                cmdFound = true;
            } else if (opt.equalsIgnoreCase("if") || opt.equalsIgnoreCase("install-framework")) {
                cmdInstallFramework(commandLine);
                cmdFound = true;
            } else if (opt.equalsIgnoreCase("empty-framework-dir")) {
                cmdEmptyFrameworkDirectory(commandLine);
                cmdFound = true;
            } else if (opt.equalsIgnoreCase("publicize-resources")) {
                cmdPublicizeResources(commandLine);
                cmdFound = true;
            }
        }
     //....................省略代码........................//
    }

由于反编译的命令是“java -jar tools/apktool_2.0.2.jar d -f -s *.apk” 所以直接查看 cmdDecode(commandLine)方法。cmdDecode方法也很长,关键代码就是try...catch...里面的decoder.decode();

private static void cmdDecode(CommandLine cli) throws AndrolibException {
         //....................省略代码........................//
        decoder.setApkFile(new File(apkName));
        try {
            decoder.decode();
        } catch (OutDirExistsException ex) {
            System.err
                    .println("Destination directory ("
                            + outDir.getAbsolutePath()
                            + ") "
                            + "already exists. Use -f switch if you want to overwrite it.");
            System.exit(1);
        } catch (InFileNotFoundException ex) {
            System.err.println("Input file (" + apkName + ") " + "was not found or was not readable.");
            System.exit(1);
        } catch (CantFindFrameworkResException ex) {
            System.err
                    .println("Can't find framework resources for package of id: "
                            + String.valueOf(ex.getPkgId())
                            + ". You must install proper "
                            + "framework files, see project website for more info.");
            System.exit(1);
        } catch (IOException ex) {
            System.err.println("Could not modify file. Please ensure you have permission.");
            System.exit(1);
        } catch (DirectoryException ex) {
            System.err.println("Could not modify internal dex files. Please ensure you have permission.");
            System.exit(1);
        } finally {
            try {
                decoder.close();
            } catch (IOException ignored) {}
        }
        System.exit(0);
    }

最后decoder.decode()里面调用了mAndrolib.recordUncompressedFiles(mApkFile, mUncompressedFiles);方法,这个方法是记录不需要压缩的文件。这是关键代码,代码很简单,可以仔细阅读。

public void recordUncompressedFiles(ExtFile apkFile, Collection uncompressedFilesOrExts) throws AndrolibException {
        try {
            Directory unk = apkFile.getDirectory();
            Set files = unk.getFiles(true);
            String ext;

            for (String file : files) {
                if (isAPKFileNames(file) && !NO_COMPRESS_PATTERN.matcher(file).find()) {
                    if (unk.getCompressionLevel(file) == 0) {

                        if (StringUtils.countMatches(file, ".") > 1) {
                            ext = file;
                        } else {
                            ext = FilenameUtils.getExtension(file);
                            if (ext.isEmpty()) {
                                ext = file;
                            }
                        }

                        if (! uncompressedFilesOrExts.contains(ext)) {
                            uncompressedFilesOrExts.add(ext);
                        }
                    }
                }
            }
        } catch (DirectoryException ex) {
            throw new AndrolibException(ex);
        }
    }

for循环遍历解压的apk所有文件,如果满足if条件就会把文件类型记录到uncompressedFilesOrExts集合中。
判断条件第一个isAPKFileNames(file)是否是apkfile,通过查看代码得知apk标准文件是下面这些

private final static String[] APK_STANDARD_ALL_FILENAMES = new String[] {
            "classes.dex", "AndroidManifest.xml", "resources.arsc", "res", "r", "R",
            "lib", "libs", "assets", "META-INF" };

判断条件第二个!NO_COMPRESS_PATTERN.matcher(file).find(),也就是不在NO_COMPRESS_PATTERN里面的文件将满足条件,NO_COMPRESS_PATTERN是一个正则表达式,如下

private final static Pattern NO_COMPRESS_PATTERN = Pattern.compile("\\.(" +
            "jpg|jpeg|png|gif|wav|mp2|mp3|ogg|aac|mpg|mpeg|mid|midi|smf|jet|rtttl|imy|xmf|mp4|" +
            "m4a|m4v|3gp|3gpp|3g2|3gpp2|amr|awb|wma|wmv|webm|mkv)$");

第三个判断条件unk.getCompressionLevel(file) == 0,这个是zip的压缩等级,源码如下

public int getCompressionLevel(String fileName)
            throws DirectoryException {
        ZipEntry entry =  mZipFile.getEntry(fileName);
        if (entry == null) {
            throw new PathNotExist("Entry not found: " + fileName);
        }
        return entry.getMethod();
    }

entry.getMethod()这个我们比较熟悉,它的值有两个

    public static final int STORED = 0;  //不压缩
    public static final int DEFLATED = 8; //压缩

如果三个判断条件都满足,将会去获取文件后缀(如果文件名类似于xxx.xxx.xxx,将会把具体的文件名加入到集合),然后把文件后缀加入到uncompressedFilesOrExts

源码我们是看明白了,结论就是只要不满足三个条件的任意一个就能解决这个问题,比较方便的就是修改NO_COMPRESS_PATTERN正则表达式,将需要压缩的文件后缀加入到表达式中,而我这次使游戏包变大的文件是json文件,所以将json后缀加入到表达式中

private final static Pattern NO_COMPRESS_PATTERN = Pattern.compile("\\.(" +
            "jpg|jpeg|png|gif|wav|mp2|mp3|ogg|aac|mpg|mpeg|mid|midi|smf|jet|rtttl|imy|xmf|mp4|" +
            "m4a|m4v|3gp|3gpp|3g2|3gpp2|amr|awb|wma|wmv|webm|mkv|json)$");

你可能感兴趣的:(使用apktool打包包体变大问题)