(五)Android多渠道打包:美团多渠道打包原理以及使用

1.传统打包:
传统的打包方法都是在AndroidManifest添加渠道标示,每打一次包修改一次标示的名称。效率特别的低,一个稍微大一点的项目打上几十个渠道包可能需要几个小时半天的时间。
2.由于传统的打包方式每次修改渠道都需要重新的构建项目,时间都浪费构建上面了,美团提供了一种新的打包方案:
Android应用使用的APK文件就是一个带签名信息的ZIP文件,根据 ZIP文件格式规范,每个ZIP文件的最后都必须有一个叫 Central Directory Record 的部分,这个CDR的最后部分叫”end of central directory record”,这一部分包含一些元数据,它的末尾是ZIP文件的注释。注释包含Comment Length和File Comment两个字段,前者表示注释内容的长度,后者是注释的内容,正确修改这一部分不会对ZIP文件造成破坏,利用这个字段,我们可以添加一些自定义的数据,Packer-Ng方式打包就是在这里添加和读取渠道信息。打包神器,100个渠道包只需5s 哈哈 。
原理很简单,就是将渠道信息存放在APK文件的注释字段中。

第一步:直接将PackerNg作为Utils拷贝到项目中。

package com.yshr.util;

import java.io.BufferedReader;
import java.io.DataInput;
import java.io.DataOutput;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.FileReader;
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;
import java.nio.MappedByteBuffer;
import java.nio.channels.FileChannel;
import java.nio.channels.FileChannel.MapMode;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

public final class PackerNg {
    private static final String TAG = PackerNg.class.getSimpleName();
    private static final String EMPTY_STRING = "";
    private static String sCachedMarket;

    public static String getMarket(final Object context) {
        return getMarket(context, EMPTY_STRING);
    }

    public static synchronized String getMarket(final Object context, final String defaultValue) {
        if (sCachedMarket == null) {
            sCachedMarket = getMarketInternal(context, defaultValue).market;
        }
        return sCachedMarket;
    }

    public static MarketInfo getMarketInfo(final Object context) {
        return getMarketInfo(context, EMPTY_STRING);
    }

    public static synchronized MarketInfo getMarketInfo(final Object context, final String defaultValue) {
        return getMarketInternal(context, defaultValue);
    }

    private static MarketInfo getMarketInternal(final Object context, final String defaultValue) {
        String market;
        Exception error;
        try {
            final String sourceDir = Helper.getSourceDir(context);
            market = Helper.readMarket(new File(sourceDir));
            error = null;
        } catch (Exception e) {
            market = null;
            error = e;
        }
        return new MarketInfo(market == null ? defaultValue : market, error);
    }

    public static class MarketInfo {
        public final String market;
        public final Exception error;

        public MarketInfo(final String market, final Exception error) {
            this.market = market;
            this.error = error;
        }

        @Override
        public String toString() {
            return "MarketInfo{" +
                    "market='" + market + '\'' +
                    ", error=" + error +
                    '}';
        }
    }

    public static class Helper {
        static final String UTF_8 = "UTF-8";
        static final int ZIP_COMMENT_MAX_LENGTH = 65535;
        static final int SHORT_LENGTH = 2;
        static final byte[] MAGIC = new byte[]{0x21, 0x5a, 0x58, 0x4b, 0x21}; //!ZXK!

        // for android code
        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 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 void writeBytes(byte[] data, DataOutput out) throws IOException {
            out.write(data);
        }

        private static 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 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);
        }


        public static void writeZipComment(File file, String comment) throws IOException {
            if (hasZipCommentMagic(file)) {
                throw new IllegalStateException("zip comment already exists, ignore.");
            }
            // {@see java.util.zip.ZipOutputStream.writeEND}
            byte[] data = comment.getBytes(UTF_8);
            final RandomAccessFile raf = new RandomAccessFile(file, "rw");
            raf.seek(file.length() - SHORT_LENGTH);
            // write zip comment length
            // (content field length + length field length + magic field length)
            writeShort(data.length + SHORT_LENGTH + MAGIC.length, raf);
            // write content
            writeBytes(data, raf);
            // write content length
            writeShort(data.length, raf);
            // write magic bytes
            writeBytes(MAGIC, raf);
            raf.close();
        }

        public static boolean hasZipCommentMagic(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);
                // check magic bytes matched
                return isMagicMatched(buffer);
            } finally {
                if (raf != null) {
                    raf.close();
                }
            }
        }

        public 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 {
                        throw new IOException("zip comment content not found");
                    }
                } else {
                    throw new IOException("zip comment magic bytes not found");
                }
            } finally {
                if (raf != null) {
                    raf.close();
                }
            }
        }

        private static String readZipCommentMmp(File file) throws IOException {
            final int mappedSize = 10240;
            final long fz = file.length();
            RandomAccessFile raf = null;
            MappedByteBuffer map = null;
            try {
                raf = new RandomAccessFile(file, "r");
                map = raf.getChannel().map(MapMode.READ_ONLY, fz - mappedSize, mappedSize);
                map.order(ByteOrder.LITTLE_ENDIAN);
                int index = mappedSize;
                byte[] buffer = new byte[MAGIC.length];
                index -= MAGIC.length;
                // read magic bytes
                map.position(index);
                map.get(buffer);
                // if magic bytes matched
                if (isMagicMatched(buffer)) {
                    index -= SHORT_LENGTH;
                    map.position(index);
                    // read content length field
                    int length = map.getShort();
                    if (length > 0) {
                        index -= length;
                        map.position(index);
                        // read content bytes
                        byte[] bytesComment = new byte[length];
                        map.get(bytesComment);
                        return new String(bytesComment, UTF_8);
                    }
                }
            } finally {
                if (map != null) {
                    map.clear();
                }
                if (raf != null) {
                    raf.close();
                }
            }
            return null;
        }


        public static void writeMarket(final File file, final String market) throws IOException {
            writeZipComment(file, market);
        }

        public static String readMarket(final File file) throws IOException {
            return readZipComment(file);
        }

        public static boolean verifyMarket(final File file, final String market) throws IOException {
            return market.equals(readMarket(file));
        }

        public static void println(String msg) {
            System.out.println(TAG + ": " + msg);
        }

        public static List<String> parseMarkets(final File file) throws IOException {
            final List<String> markets = new ArrayList<String>();
            FileReader fr = new FileReader(file);
            BufferedReader br = new BufferedReader(fr);
            String line = null;
            int lineNo = 1;
            while ((line = br.readLine()) != null) {
                String parts[] = line.split("#");
                if (parts.length > 0) {
                    final String market = parts[0].trim();
                    if (market.length() > 0) {
                        markets.add(market);
                    } else {
                        println("skip invalid market line " + lineNo + ":'" + line + "'");
                    }
                } else {
                    println("skip invalid market line" + lineNo + ":'" + line + "'");
                }
                ++lineNo;
            }
            br.close();
            fr.close();
            return markets;
        }

        public static void copyFile(File src, File dest) throws IOException {
            if (!dest.exists()) {
                dest.createNewFile();
            }
            FileChannel source = null;
            FileChannel destination = null;
            try {
                source = new FileInputStream(src).getChannel();
                destination = new FileOutputStream(dest).getChannel();
                destination.transferFrom(source, 0, source.size());
            } finally {
                if (source != null) {
                    source.close();
                }
                if (destination != null) {
                    destination.close();
                }
            }
        }

        public static boolean deleteDir(File dir) {
            File[] files = dir.listFiles();
            if (files == null || files.length == 0) {
                return false;
            }
            for (File file : files) {
                if (file.isDirectory()) {
                    deleteDir(file);
                } else {
                    file.delete();
                }
            }
            return true;
        }

        public static String getExtension(final String fileName) {
            int dot = fileName.lastIndexOf(".");
            if (dot > 0) {
                return fileName.substring(dot + 1);
            } else {
                return null;
            }
        }

        public static String getBaseName(final String fileName) {
            int dot = fileName.lastIndexOf(".");
            if (dot > 0) {
                return fileName.substring(0, dot);
            } else {
                return fileName;
            }
        }
    }

    public static void main(String[] args) throws Exception {
        if (args.length < 2) {
            Helper.println("Usage: java -jar packer-ng-x.x.x.jar your_apk_file market_file");
            System.exit(1);
        }
        Helper.println("command args: " + Arrays.toString(args));
        File apkFile = new File(args[0]);
        final File marketFile = new File(args[1]);
        if (!apkFile.exists()) {
            Helper.println("apk file:" + apkFile + " not exists or not readable");
            System.exit(1);
            return;
        }
        if (!marketFile.exists()) {
            Helper.println("markets file:" + marketFile + " not exists or not readable");
            System.exit(1);
            return;
        }
        Helper.println("apk file: " + apkFile);
        Helper.println("market file: " + marketFile);
        List<String> markets = Helper.parseMarkets(marketFile);
        if (markets == null || markets.isEmpty()) {
            Helper.println("not markets found.");
            System.exit(1);
            return;
        }
        Helper.println("markets: " + markets);
        final String baseName = Helper.getBaseName(apkFile.getName());
        final String extName = Helper.getExtension(apkFile.getName());
        final File outputDir = new File("apks");
        if (!outputDir.exists()) {
            outputDir.mkdirs();
        } else {
            Helper.deleteDir(outputDir);
        }
        int processed = 0;
        for (final String market : markets) {
            String apkName = "supermarket_" + market + "." + extName;

            try {
                String apkNameRule = args[2];
                apkName = String.format(apkNameRule, market);
            } catch (Exception exception) {

            }

            File destFile = new File(outputDir, apkName);
            Helper.copyFile(apkFile, destFile);
            Helper.writeMarket(destFile, market);
            if (Helper.verifyMarket(destFile, market)) {
                ++processed;
                Helper.println("processed apk " + destFile.getAbsolutePath() + "/" + apkName);
            } else {
                destFile.delete();
                Helper.println("failed to process " + apkName);
            }
        }
        Helper.println("all " + processed + " processed apks saved to " + outputDir);
    }

}

第二步:创建一个保存渠道包名的txt文件,可以放在项目主目录下:比如命名market.txt
渠道名可以按照需求随便添加
anzhi
baidu
huawei
legend
letv
meizu
oppo
qq
PC
sougou
UC
update
update1
vivo
wandoujia
woshangdian
xiaomi

第三步:ChannelUtil这个工具类是用于取出文件里的渠道名

package com.yshr.util;

import android.content.Context;
import android.text.TextUtils;

import com.ztx.shudu.supermarket.app.App;
import com.ztx.shudu.supermarket.app.Constants;
import com.ztx.shudu.supermarket.model.prefs.ImplPreferencesHelper;

public class ChannelUtil {

    private static String mChannel;

    /**
     * 返回市场。  如果获取失败返回""
     *
     * @param context
     * @return
     */
    public static String getChannel(Context context) {
        return getChannel(context, "default");
//        return getChannel(context, "sjzs360");
    }

    /**
     * 返回市场。  如果获取失败返回defaultChannel
     *
     * @param context
     * @param defaultChannel
     * @return
     */
    public static String getChannel(Context context, String defaultChannel) {
        //内存中获取
        if (!TextUtils.isEmpty(mChannel)) {
            return mChannel;
        }
        //sp中获取
        mChannel = getChannelBySharedPreferences(context);
        if (!TextUtils.isEmpty(mChannel)) {
            return mChannel;
        }
        mChannel = PackerNg.getMarket(context);
        if (!TextUtils.isEmpty(mChannel)) {
            //保存sp中备用
            saveChannelBySharedPreferences(context, mChannel);
            return mChannel;
        }
        //全部获取失败
        return defaultChannel;
    }

    /**
     * 本地保存channel & 对应版本号
     *
     * @param context
     * @param channel
     */
    private static void saveChannelBySharedPreferences(Context context, String channel) {
//        SharedPreferencesUtil.getInstance(context).applyString(Constants.Companion.getSUPERMARKET_CHANNEL(), channel);
        App.instance.getSharedPreferences(ImplPreferencesHelper.Companion.getSHAREDPREFERENCES_NAME(), Context.MODE_PRIVATE).edit().putString(Constants.Companion.getSUPERMARKET_CHANNEL(), "").apply();
    }

    /**
     * 从sp中获取channel
     *
     * @param context
     * @return 为空表示获取异常、sp中的值已经失效、sp中没有此值
     */
    private static String getChannelBySharedPreferences(Context context) {
//        return SharedPreferencesUtil.getInstance(context).getString(Constants.SUPERMARKET_CHANNEL);
        return App.instance.getSharedPreferences(ImplPreferencesHelper.Companion.getSHAREDPREFERENCES_NAME(), Context.MODE_PRIVATE).getString(Constants.Companion.getSUPERMARKET_CHANNEL(), "");

    }

}

第四步:打开第二步中的PackerNg类,首先配置一下此类main函数中接受的参数信息。本事例通过Android Studio的方式进行配置直接上图:


20170227183454058.png

图中标注3的位置就是PackerNg类配置main函数中接受的两个参数: 第一个参数为默认的release包的apk源文件,包名为ChannelUtil起初默认的包名


default.jpg

第二个参数为保存渠道名的文件 这两个参数路径直接可以拖过来
第五步:在Application类中onCreate方法中添加代码
val channel = ChannelUtil.getChannel(applicationContext) //Kotlin语法

拿到这个包名可以传给后台进行统计或进行其它的操作。

第六步:运行PackerNg类,会在项目目录下自动生成文件夹apks(在PackerNg.java文件中配置好的apk渠道包存储路径)


20170227184051749.png

注意点:第四步中ChannelUtil起初默认的包名为源文件,其它所有的的渠道包都是通过PackerNg打包方式都是以这个源文件为模版,进行复制,将不同的渠道名复制给这个源文件。如果是360渠道上线的话需要将这个包名默认改为360的渠道单独打包,因为360上线需要加固,会把之前通过源文件复制渠道名给抹掉,所以对于360加固的文件需要单独把360作为源文件来打包不改为360默认的渠道包后会统计不到360渠道的信息。

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

推荐阅读更多精彩内容

  • 关于作者: 李涛,腾讯Android工程师,14年加入腾讯SNG增值产品部,期间主要负责手Q动漫、企鹅电竞等项目的...
    稻草人_3e17阅读 3,574评论 0 10
  • Android 自定义View的各种姿势1 Activity的显示之ViewRootImpl详解 Activity...
    passiontim阅读 171,045评论 25 707
  • Spring Cloud为开发人员提供了快速构建分布式系统中一些常见模式的工具(例如配置管理,服务发现,断路器,智...
    卡卡罗2017阅读 134,494评论 18 139
  • 目录一、Python打包及优化(美团多渠道打包)二、Gradle打包三、其他打包方案:修改Zip文件的commen...
    守望君阅读 5,665评论 4 17
  • 刚刚撕逼大战结束,这次好像没有之前那么累,但是心寒。一个大公司规章制度靠老板的心情,姐姐我也是醉了。一边要尽全力的...
    艳敏姐阅读 842评论 4 4