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 Length 和 File 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进行插件开发,我在下一篇文章中来记录。