天天看点

分享一种最简单的Android打渠道包的方法

转载自:http://blog.csdn.net/wei1583812/article/details/44463697

做Android开发一转眼就四年了,以前是用ant打包的,习惯了也没觉得慢。

今年年初加入了新公司,新公司用的是Android studio开发,用的是gradle构建项目。

由于gradle构建每次都是重新编译项目,所以打包时就特别慢了,16个渠道包要打一个小时吧。

然后我们的项目负责人就交给我一个任务,研究下有什么快的打包方法,

并发给我一篇参考文章:http://tech.meituan.com/mt-apk-packaging.html

我一边写代码一边测试,终于找到了一种很快的打渠道包的方法。

因为APK其实就是ZIP的格式,所以,解压apk后,会看到里面有个META-INF目录。

由于META-INF目录并不会影响到APK的签名和运行,所以我们可以在META-INF目录里添加一个空文件,

不同的渠道就添加不同的空文件,文件名代表不同的渠道。

代码是java写的:

[java]  view plain copy

  1. public class Tool {  
  2.     private static final String CHANNEL_PREFIX = "/META-INF/";  
  3.     private static final String CHANNEL_PATH_MATCHER = "regex:/META-INF/mtchannel_[0-9a-zA-Z]{1,5}";  
  4.     private static String source_path;  
  5.     private static final String channel_file_name = "channel_list.txt";  
  6.     private static final String channel_flag = "channel_";  
  7.     public static void main(String[] args) throws Exception {  
  8.         if (args.length <= 0) {  
  9.             System.out.println("请输入文件路径作为参数");  
  10.             return;  
  11.         }  
  12.         final String source_apk_path = args[0];//main方法传入的源apk的路径,是执行jar时命令行传入的,不懂的往下看。  
  13.         int last_index = source_apk_path.lastIndexOf("/") + 1;  
  14.         source_path = source_apk_path.substring(0, last_index);  
  15.         final String source_apk_name = source_apk_path.substring(last_index, source_apk_path.length());  
  16.         System.out.println("包路径:" + source_path);  
  17.         System.out.println("文件名:" + source_apk_name);  
  18.         ArrayList<String> channel_list = getChannelList(source_path + channel_file_name);  
  19.         final String last_name = ".apk";  
  20.         for (int i = 0; i < channel_list.size(); i++) {  
  21.             final String new_apk_path = source_path + source_apk_name.substring(0, source_apk_name.length() - last_name.length()) //  
  22.                     + "_" + channel_list.get(i) + last_name;  
  23.             copyFile(source_apk_path, new_apk_path);  
  24.             changeChannel(new_apk_path, channel_flag + channel_list.get(i));  
  25.         }  
  26.     }  
  27.     public static boolean changeChannel(final String zipFilename, final String channel) {  
  28.         try (FileSystem zipfs = createZipFileSystem(zipFilename, false)) {  
  29.             final Path root = zipfs.getPath("/META-INF/");  
  30.             ChannelFileVisitor visitor = new ChannelFileVisitor();  
  31.             Files.walkFileTree(root, visitor);  
  32.             Path existChannel = visitor.getChannelFile();  
  33.             Path newChannel = zipfs.getPath(CHANNEL_PREFIX + channel);  
  34.             if (existChannel != null) {  
  35.                 Files.move(existChannel, newChannel, StandardCopyOption.ATOMIC_MOVE);  
  36.             } else {  
  37.                 Files.createFile(newChannel);  
  38.             }  
  39.             return true;  
  40.         } catch (IOException e) {  
  41.             System.out.println("添加渠道号失败:" + channel);  
  42.             e.printStackTrace();  
  43.         }  
  44.         return false;  
  45.     }  
  46.     private static FileSystem createZipFileSystem(String zipFilename, boolean create) throws IOException {  
  47.         final Path path = Paths.get(zipFilename);  
  48.         final URI uri = URI.create("jar:file:" + path.toUri().getPath());  
  49.         final Map<String, String> env = new HashMap<>();  
  50.         if (create) {  
  51.             env.put("create", "true");  
  52.         }  
  53.         return FileSystems.newFileSystem(uri, env);  
  54.     }  
  55.     private static class ChannelFileVisitor extends SimpleFileVisitor<Path> {  
  56.         private Path channelFile;  
  57.         private PathMatcher matcher = FileSystems.getDefault().getPathMatcher(CHANNEL_PATH_MATCHER);  
  58.         public Path getChannelFile() {  
  59.             return channelFile;  
  60.         }  
  61.         @Override  
  62.         public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException {  
  63.             if (matcher.matches(file)) {  
  64.                 channelFile = file;  
  65.                 return FileVisitResult.TERMINATE;  
  66.             } else {  
  67.                 return FileVisitResult.CONTINUE;  
  68.             }  
  69.         }  
  70.     }  
  71.     private static ArrayList<String> getChannelList(String filePath) {  
  72.         ArrayList<String> channel_list = new ArrayList<String>();  
  73.         try {  
  74.             String encoding = "UTF-8";  
  75.             File file = new File(filePath);  
  76.             if (file.isFile() && file.exists()) { // 判断文件是否存在  
  77.                 InputStreamReader read = new InputStreamReader(new FileInputStream(file), encoding);// 考虑到编码格式  
  78.                 BufferedReader bufferedReader = new BufferedReader(read);  
  79.                 String lineTxt = null;  
  80.                 while ((lineTxt = bufferedReader.readLine()) != null) {  
  81.                     // System.out.println(lineTxt);  
  82.                     if (lineTxt != null && lineTxt.length() > 0) {  
  83.                         channel_list.add(lineTxt);  
  84.                     }  
  85.                 }  
  86.                 read.close();  
  87.             } else {  
  88.                 System.out.println("找不到指定的文件");  
  89.             }  
  90.         } catch (Exception e) {  
  91.             System.out.println("读取文件内容出错");  
  92.             e.printStackTrace();  
  93.         }  
  94.         return channel_list;  
  95.     }  
  96.     private static void copyFile(final String source_file_path, final String target_file_path) throws IOException {  
  97.         File sourceFile = new File(source_file_path);  
  98.         File targetFile = new File(target_file_path);  
  99.         BufferedInputStream inBuff = null;  
  100.         BufferedOutputStream outBuff = null;  
  101.         try {  
  102.             // 新建文件输入流并对它进行缓冲  
  103.             inBuff = new BufferedInputStream(new FileInputStream(sourceFile));  
  104.             // 新建文件输出流并对它进行缓冲  
  105.             outBuff = new BufferedOutputStream(new FileOutputStream(targetFile));  
  106.             // 缓冲数组  
  107.             byte[] b = new byte[1024 * 5];  
  108.             int len;  
  109.             while ((len = inBuff.read(b)) != -1) {  
  110.                 outBuff.write(b, 0, len);  
  111.             }  
  112.             // 刷新此缓冲的输出流  
  113.             outBuff.flush();  
  114.         } catch (Exception e) {  
  115.             System.out.println("复制文件失败:" + target_file_path);  
  116.             e.printStackTrace();  
  117.         } finally {  
  118.             // 关闭流  
  119.             if (inBuff != null)  
  120.                 inBuff.close();  
  121.             if (outBuff != null)  
  122.                 outBuff.close();  
  123.         }  
  124.     }  
  125. }  

1、新建一个java工程,把上面的代码复制进去。

2、对着这个类点右键,选择Export-java-Runnable JAR file

3、在Launch configuration中,选择你所要导出的类(如果这里不能选择,那么你要run一下你的工程,run成功了才能选择你要导为jar的类),

假设导出的jar的名字是apktool.jar

然后在命令行输入:

[plain]  view plain copy

  1. java -jar /Users/company/Documents/apk/apktool.jar /Users/company/Documents/apk/test.apk  

我用的mac电脑,路径和windows不一样,上面的路径都是拖拽进命令行的。

[plain]  view plain copy

  1. /Users/company/Documents/apk/apktool.jar 表示jar包所在路径;  

[plain]  view plain copy

  1. /Users/company/Documents/apk/test.apk表示你源apk路径,这个是作为命令行参数传入main方法的。  

test.apk就是你已经打包成功的一个apk,就是源apk,在你源apk的基础上生成渠道包。

channel_list.text一定要和这个源apk在同一个目录下。

比如channel_list.text里面的数据结构如下:

[plain]  view plain copy

  1. 360  
  2. xiaomi  
  3. anzhi  
  4. baidu  

运行命令后,你会发现在channel_list.text和源apk目录下,会生成你想要的渠道包。

你可以把扩展名改为.zip,然后解压看看是否在META-INF目录下生成你想要的渠道名文件。

最后,就是读取这个渠道标识了,代码是写在Android工程里的,代码如下:

[java]  view plain copy

  1. private static String channel = null;      
  2. public static String getChannel(Context context) {  
  3.         if (channel != null) {  
  4.             return channel;  
  5.         }  
  6.         final String start_flag = "META-INF/channel_";  
  7.         ApplicationInfo appinfo = context.getApplicationInfo();  
  8.         String sourceDir = appinfo.sourceDir;  
  9.         ZipFile zipfile = null;  
  10.         try {  
  11.             zipfile = new ZipFile(sourceDir);  
  12.             Enumeration<?> entries = zipfile.entries();  
  13.             while (entries.hasMoreElements()) {  
  14.                 ZipEntry entry = ((ZipEntry) entries.nextElement());  
  15.                 String entryName = entry.getName();  
  16.                 if (entryName.contains(start_flag)) {  
  17.                     channel = entryName.replace(start_flag, "");  
  18.                     break;  
  19.                 }  
  20.             }  
  21.         } catch (IOException e) {  
  22.             e.printStackTrace();  
  23.         } finally {  
  24.             if (zipfile != null) {  
  25.                 try {  
  26.                     zipfile.close();  
  27.                 } catch (IOException e) {  
  28.                     e.printStackTrace();  
  29.                 }  
  30.             }  
  31.         }  
  32.         if (channel == null || channel.length() <= 0) {  
  33.             channel = "guanwang";//读不到渠道号就默认是官方渠道  
  34.         }  
  35.         return channel;  
  36.     }  

如果你用的友盟统计,可以在主Activity里这么写:AnalyticsConfig.setChannel("获取到的渠道");

好了,结束了,有问题留言。