Android 基于gradle插件实现多渠道打包

首先声明,技术方案不是我想出来的,我只是写了插件的实现,要感谢大神研究出的渠道打包方案。

方案一

http://tech.meituan.com/mt-apk-packaging.html

基于META-INF目录下添加空文件的方式区分不同的渠道包,因为META-INF目录是不进入签名计算的,所以修改里面的文件是不需要重新计算签名的,主要的时间消耗在复制文件和向zip包中压缩空文件这块的耗时。

打包插件代码如下:

import net.lingala.zip4j.core.ZipFile
import net.lingala.zip4j.model.ZipParameters
import org.apache.commons.io.FileUtils
import org.gradle.api.Plugin
import org.gradle.api.Project

import net.lingala.zip4j.util.Zip4jConstants;
public class MakeChannelPlugin implements Plugin<Project> {

    @Override
    void apply(Project project) {
        project.extensions.create("makeChannel", MakeChannelParams);
        project.task('makeChannel') << {
            File channelFile = project.file(project.makeChannel.channelFile)
            if (!channelFile.exists()) {
                println("channelFile路径错误")
                return;
            }
            FileReader reader = new FileReader(channelFile.absolutePath);
            File inputApk = project.file(project.makeChannel.inputApk);
            if (!inputApk.exists()) {
                println("inputApk路径错误")
                return;
            }
            File output = project.file(project.makeChannel.outputDir);
            if (!output.exists()) {
                output.mkdir();
            }

            BufferedReader br = new BufferedReader(reader);
            String str = null;
            long time = System.currentTimeMillis() / 1000;
            while ((str = br.readLine()) != null) {
                String channel = str.trim();
                def apkName = channel + ".signed.apk"
                File outFile = new File(output, apkName);
                copy(inputApk, outFile);
                ZipFile zipFile = new ZipFile(outFile);
                ZipParameters parameters = new ZipParameters();
                parameters.setCompressionMethod(Zip4jConstants.COMP_DEFLATE);
                parameters.setCompressionLevel(Zip4jConstants.DEFLATE_LEVEL_NORMAL);
                parameters.setRootFolderInZip("META-INF/");
                File newFile = new File(output, project.makeChannel.baseChannelName + "_" + channel);
                if (!newFile.exists()) {
                    newFile.createNewFile();
                }
                zipFile.addFile(newFile, parameters);
                println("生成文件 " + apkName);
                newFile.delete();
            }
            println("耗时" + (System.currentTimeMillis() / 1000 - time) + "秒");
            br.close();
            reader.close();
        };
    }

    private static void copy(File sourceFilePath, File copyFilePath) {
        try {
            FileUtils.copyFile(sourceFilePath, copyFilePath);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    private static class MakeChannelParams {
        String channelFile = "../appbuild/channels"; // channel文件目录地址
        String inputApk = ""; // 输入apk路径
        String outputDir = "../appbuild/output"; // 输出文件目录
        String baseChannelName = "channel" // 默认channel
    }
}

这里用到了两个依赖, 'org.apache.commons:commons-io:1.3.2'和 'net.lingala.zip4j:zip4j:1.3.2',其中common-io主要使用了复制文件的方法,可以选择自己实现文件复制过程,zip4j包的作用主要是向META-INF目录下添加一个名为channel_渠道名的空文件。

Snip20170209_22.png

大概365个包耗时64秒,还是有点长的,美团的python脚本打包的时间大概为52秒,这是由于java和python本身的特性决定的。

接下来看获取渠道的代码:

       private static String getChannel(Context context, String startsWith) {
            ApplicationInfo appinfo = context.getApplicationInfo();
            String sourceDir = appinfo.sourceDir;
            String ret = "";
            ZipFile zipfile = null;
            try {
                zipfile = new ZipFile(sourceDir);
                Enumeration<?> entries = zipfile.entries();
                while (entries.hasMoreElements()) {
                    ZipEntry entry = ((ZipEntry) entries.nextElement());
                    String entryName = entry.getName();
                    if (entryName.startsWith(startsWith)) {
                        ret = entryName;
                        break;
                    }
                }
            } catch (IOException e) {
                e.printStackTrace();
            } finally {
                if (zipfile != null) {
                    try {
                        zipfile.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            }
            String[] split = ret.split("_");
            if (split.length >= 2) {
                try {
                    channel = URLEncoder.encode(ret.substring(split[0].length() + 1).trim(), "UTF-8");
                } catch (UnsupportedEncodingException e) {
                    channel = "android";
                }
            } else {
                channel = "android";
            }
        }

注意这里有个startsWith的字符串,这个字符串跟刚才插件中提到的baseChannelName必须统一,才能获取到渠道名,最终的channel变量就是渠道名。

方案二

http://blog.csdn.net/lazyer_dog/article/details/52919743

Android应用使用的APK文件就是一个带签名信息的ZIP文件,根据 ZIP文件格式规范 ,每个ZIP文件的最后都必须有一个叫 Central Directory Record 的部分,这个CDR的最后部分叫"end of central directory record",这一部分包含一些元数据,它的末尾是ZIP文件的注释。注释包含 Comment LengthFile Comment 两个字段,前者表示注释内容的长度,后者是注释的内容,正确修改这一部分不会对ZIP文件造成破坏,利用这个字段,我们可以添加一些自定义的数据。

方案二主要是利用了这个原理,将渠道信息写入了comment中,并从comment中读出。插件代码如下:

import org.apache.commons.io.FileUtils
import org.gradle.api.Plugin
import org.gradle.api.Project

import java.nio.ByteBuffer
import java.nio.ByteOrder;

public class MakeChannelPlugin2 implements Plugin<Project> {

    @Override
    void apply(Project project) {
        project.extensions.create("makeChannel2", MakeChannelParams);
        project.task('makeChannel2') << {
            File channelFile = project.file(project.makeChannel2.channelFile)
            if (!channelFile.exists()) {
                println("channelFile路径错误")
                return;
            }
            FileReader reader = new FileReader(channelFile.absolutePath);
            File inputApk = project.file(project.makeChannel2.inputApk);
            if (!inputApk.exists()) {
                println("inputApk路径错误")
                return;
            }
            File output = project.file(project.makeChannel2.outputDir);
            if (!output.exists()) {
                output.mkdir();
            }

            BufferedReader br = new BufferedReader(reader);
            String str = null;
            long time = System.currentTimeMillis() / 1000;
            while ((str = br.readLine()) != null) {
                String channel = str.trim();
                writeComment(output.getAbsolutePath(), inputApk, channel);
            }
            println("耗时" + (System.currentTimeMillis() / 1000 - time) + "秒");
            br.close();
            reader.close();
        };
    }
    private static byte[] MAGIC = new byte[5];

    static {
        MAGIC[0] = 0x21;
        MAGIC[1] = 0x5a;
        MAGIC[2] = 0x58;
        MAGIC[3] = 0x4b;
        MAGIC[4] = 0x21;
    }
    private static final int SHORT_LENGTH = 2;

    private void writeComment(String outputDir, File originalApkFile, String channel) {
        try {
            String originalApkFileName = originalApkFile.getName();
            int index = originalApkFileName.indexOf(".apk");
            if (index == -1) {
                return;
            }

            def apkName = channel + ".signed.apk"
            File destApkFile = new File(outputDir, apkName);
            boolean success = destApkFile.createNewFile();
            if (!success) {
                return;
            }
            FileUtils.copyFile(originalApkFile, destApkFile);

            RandomAccessFile raf = new RandomAccessFile(destApkFile.getAbsolutePath(), "rw");
            raf.seek(destApkFile.length() - 2);
            writeShort((short) (channel.getBytes("UTF-8").length + 2 + MAGIC.length), raf);
            raf.write(channel.getBytes("UTF-8"));
            writeShort((short) channel.getBytes("UTF-8").length, raf);
            raf.write(MAGIC);
            raf.close();
            println("生成文件 " + apkName);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    private void writeShort(int i, DataOutput out) throws IOException {
        ByteBuffer bb = ByteBuffer.allocate(SHORT_LENGTH).order(ByteOrder.LITTLE_ENDIAN);
        bb.putShort((short) i);
        out.write(bb.array());
    }

    private static class MakeChannelParams {
        String channelFile = "../appbuild/channels"; // channel文件目录地址
        String inputApk = ""; // 输入apk路径
        String outputDir = "../appbuild/output"; // 输出文件目录
    }
}

获取渠道代码如下:

import java.io.DataInput;
import java.io.File;
import java.io.IOException;
import java.io.RandomAccessFile;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.nio.ByteBuffer;
import java.nio.ByteOrder;

public class ChannelHelper {

    public static String getChannel(final Object context) {
        try {
            String sourceDir = getSourceDir(context);
            return readZipComment(new File(sourceDir));
        } catch (Exception e) {
            e.printStackTrace();
        }
        return "android";

    }

    private static String getSourceDir(final Object context)
            throws ClassNotFoundException,
            InvocationTargetException,
            IllegalAccessException,
            NoSuchFieldException,
            NoSuchMethodException {
        final Class<?> contextClass = Class.forName("android.content.Context");
        final Class<?> applicationInfoClass = Class.forName("android.content.pm.ApplicationInfo");
        final Method getApplicationInfoMethod = contextClass.getMethod("getApplicationInfo");
        final Object appInfo = getApplicationInfoMethod.invoke(context);
        // try ApplicationInfo.publicSourceDir
        final Field publicSourceDirField = applicationInfoClass.getField("publicSourceDir");
        String sourceDir = (String) publicSourceDirField.get(appInfo);
        if (sourceDir == null) {
            // try ApplicationInfo.sourceDir
            final Field sourceDirField = applicationInfoClass.getField("sourceDir");
            sourceDir = (String) sourceDirField.get(appInfo);
        }
        if (sourceDir == null) {
            // try Context.getPackageCodePath()
            final Method getPackageCodePathMethod = contextClass.getMethod("getPackageCodePath");
            sourceDir = (String) getPackageCodePathMethod.invoke(context);
        }
        return sourceDir;

    }

    private static final byte[] MAGIC = new byte[]{0x21, 0x5a, 0x58, 0x4b, 0x21}; //!ZXK!

    private static String readZipComment(File file) throws IOException {
        RandomAccessFile raf = null;
        try {
            raf = new RandomAccessFile(file, "r");
            long index = raf.length();
            byte[] buffer = new byte[MAGIC.length];
            index -= MAGIC.length;
            // read magic bytes
            raf.seek(index);
            raf.readFully(buffer);
            // if magic bytes matched
            if (isMagicMatched(buffer)) {
                index -= SHORT_LENGTH;
                raf.seek(index);
                // read content length field
                int length = readShort(raf);
                if (length > 0) {
                    index -= length;
                    raf.seek(index);
                    // read content bytes
                    byte[] bytesComment = new byte[length];
                    raf.readFully(bytesComment);
                    return new String(bytesComment, "UTF-8");
                } else {
                    return "android";
                }
            } else {
                return "android";
            }
        } finally {
            if (raf != null) {
                raf.close();
            }
        }
    }

    private static boolean isMagicMatched(byte[] buffer) {
        if (buffer.length != MAGIC.length) {
            return false;
        }
        for (int i = 0; i < MAGIC.length; ++i) {
            if (buffer[i] != MAGIC[i]) {
                return false;
            }
        }
        return true;
    }

    private static final int SHORT_LENGTH = 2;

    private static short readShort(DataInput input) throws IOException {
        byte[] buf = new byte[SHORT_LENGTH];
        input.readFully(buf);
        ByteBuffer bb = ByteBuffer.wrap(buf).order(ByteOrder.LITTLE_ENDIAN);
        return bb.getShort(0);
    }
}

结果如下:

Snip20170210_25.png

时间减少到25秒,相当于减半,还是有很大的提升的。

至于如何使用groovy进行插件开发,我在下一篇文章中来记录。

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 159,290评论 4 363
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 67,399评论 1 294
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 109,021评论 0 243
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 44,034评论 0 207
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 52,412评论 3 287
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 40,651评论 1 219
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 31,902评论 2 313
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 30,605评论 0 199
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 34,339评论 1 246
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 30,586评论 2 246
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 32,076评论 1 261
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 28,400评论 2 253
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 33,060评论 3 236
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 26,083评论 0 8
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 26,851评论 0 195
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 35,685评论 2 274
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 35,595评论 2 270

推荐阅读更多精彩内容