承接上文Android應(yīng)用的自動化構(gòu)建,我們已經(jīng)通過ANT自動構(gòu)建了應(yīng)用,那接下來的問題是,如何自動構(gòu)建渠道包,這里強(qiáng)烈推薦一篇文章美團(tuán)Android自動化之旅—生成渠道包。
美團(tuán)提到的第三種方式,截圖如下:

本文主要以這種方式,來實(shí)現(xiàn)Android渠道包的自動生成。
Demo文件結(jié)構(gòu)如下:

其中,empty是需要寫入apk的空文件,channel文件為渠道列表,內(nèi)容如下:
wandoujia
meituan
yingyongbao
最重要的是python腳本文件,實(shí)現(xiàn)如下:
import os
import os.path
import shutil
import zipfile
pkgPath = os.getcwd() + "/channelApk"
isPathExist = os.path.exists(pkgPath)
if isPathExist != True:
os.mkdir(pkgPath)
f = open('channel','r')
for line in f :
channelPath = pkgPath+"/ant-release_{temp}.apk".format(temp = line.strip('\n'))
shutil.copy("ant-release.apk", channelPath)
zipped = zipfile.ZipFile(channelPath, 'a', zipfile.ZIP_DEFLATED)
empty_channel_file = "META-INF/mtchannel_{channel}".format(channel=line.strip('\n'))
zipped.write("empty", empty_channel_file)
python代碼很容易理解,就是把原本的apk,重命名復(fù)制一份到指定的channelApk目錄下,然后再向重命名后的apk里面寫入空文件,生成渠道包。
執(zhí)行腳本后文件目錄如下:

可以看到,已經(jīng)生成了渠道包:

我們解壓其中一個渠道包可以看到,確實(shí)寫入了該渠道路徑的空文件:

通過簡單的腳本文件,我們已經(jīng)實(shí)現(xiàn)了渠道包的自動生成,最后附上識別渠道包的java代碼:
public class ChannelTools {
public static String getChannel(Context context) {
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();
Log.i("ANTDEMO", "entryName : " + entryName);
if (entryName.startsWith("META-INF/mtchannel")) {
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 != null && split.length >= 2) {
return ret.substring(split[0].length() + 1);
} else {
return "";
}
}
}