ChannelUtil.java 2.07 KB
package com.cnlive.goldenline.util;

import android.content.Context;
import android.content.pm.ApplicationInfo;
import android.support.annotation.NonNull;

import com.cnlive.goldenline.BuildConfig;
import com.orhanobut.logger.Logger;

import java.io.IOException;
import java.util.Enumeration;
import java.util.zip.ZipEntry;
import java.util.zip.ZipFile;

/**
 * Created by zuoxian on 15/9/7.
 */
public class ChannelUtil {
    private static final String CHANGE_TAG = "cztchannel_";

    /**
     * 从apk中获取版本信息
     * @param context
     * @return
     */
    @NonNull
    public static String getChannelFromApk(@NonNull Context context) {
        //从apk包中获取
        ApplicationInfo appinfo = context.getApplicationInfo();
        String sourceDir = appinfo.sourceDir;
        //注意这里:默认放在meta-inf/里, 所以需要再拼接一下
        String key = "META-INF/" + CHANGE_TAG;
        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(key)) {
                    ret = entryName;
                    break;
                }
            }
        } catch (IOException e) {
            Logger.e(e, e.getMessage());
        } finally {
            if (zipfile != null) {
                try {
                    zipfile.close();
                    System.gc();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if(BuildConfig.DEBUG){
                ret = "cztchannel_20151031";
            }
        }
        String[] split = ret.split("_");
        String channel = "debug";
        if (split != null && split.length >= 2) {
            channel = ret.substring(split[0].length() + 1);
        }
        Logger.e("frmId:" + channel);
        return channel;
    }
}