当前位置:首页 >热点 >Android渠道打包技术小结 以我们的道打App为例

Android渠道打包技术小结 以我们的道打App为例

2024-05-21 22:06:54 [百科] 来源:避面尹邢网

Android渠道打包技术小结

作者:贼寇 移动开发 Android 与iOS的道打单一渠道(AppStore)不同,Android平台在国内的包技渠道多入牛毛。以我们的道打App为例,就有27个普通渠道(应用宝,包技百度,道打360这种)和更多的包技推广专用渠道。我们打包技术也经过了若干次的道打改进。

导读

本文对比了渠道4种渠道打包方式: 

Android渠道打包技术小结 以我们的道打App为例

 

Android渠道打包技术小结 以我们的道打App为例

 

Android渠道打包技术小结 以我们的道打App为例

 

与iOS的包技单一渠道(AppStore)不同,Android平台在国内的道打渠道多入牛毛。以我们的包技App为例,就有27个普通渠道(应用宝,道打百度,包技360这种)和更多的道打推广专用渠道。我们打包技术也经过了若干次的包技改进。

1.利用Gradle Product Favor打包

  1. android {  
  2.     productFlavors {  
  3.         base {  
  4.             manifestPlaceholders = [ CHANNEL:”0"] 
  5.         } 
  6.         yingyongbao {  
  7.             manifestPlaceholders = [ CHANNEL:"1" ] 
  8.         } 
  9.         baidu {  
  10.             manifestPlaceholders = [ CHANNEL:"2"] 
  11.         } 
  12.     } 
  13. }  

AndroidManifest.xml

  1. <!-- 自用渠道号设置 --> 
  2. <meta-data 
  3.      android:name="CHANNEL" 
  4.      android:value="${ CHANNEL}”/>  

原理很简单,道打gradle编译的时候,会根据这个配置,把manifest里对应的metadata占位符替换成指定的值。然后Android这边在运行期再去取出来就是:

  1. public static String getChannel(Context context) {  
  2.     String channel = ""; 
  3.     PackageManager pm = sContext.getPackageManager(); 
  4.     try {  
  5.         ApplicationInfo ai = pm.getApplicationInfo( 
  6.             context.getPackageName(), 
  7.             PackageManager.GET_META_DATA); 
  8.  
  9.         String value = ai.metaData.getString("CHANNEL"); 
  10.         if (value != null) {  
  11.             channel = value; 
  12.         } 
  13.     } catch (Exception e) {  
  14.         // 忽略找不到包信息的异常 
  15.     } 
  16.     return channel; 
  17. }    

这个办法,缺点很明显,每打一个渠道包都会完整得执行一遍apk的编译打包流程,非常慢。近30个包要打一个多小时…优点就是不依赖其他工具,gradle自己就能搞定。

2.替换Assets资源打包

assets用于存放一些资源。不同与res,assets里的资源编译时原样保留,不需要生成什么resouce id之类的东西。因此,我们可以通过替换assets里的文件打出不同的渠道包,而不用每次都重新编译。

我们知道apk本质上就是个zip文件,那么我们就可以通过解压缩->替换文件->压缩的办法来搞定:

这里给出一份Python3的实现

  1. # 解压缩 
  2. src_file_path = '原始apk文件路径' 
  3. extract_dir = '解压的目标目录路径' 
  4. os.makedirs(extract_dir, exist_ok=True) 
  5.  
  6. os.system(UNZIP_PATH + ' -o -d %s %s' % (extract_dir, src_file_path)) 
  7.  
  8. # 删除签名信息 
  9. shutil.rmtree(os.path.join(extract_dir, 'META-INF')) 
  10.  
  11. # 写入渠道文件assets/channel.conf 
  12. channel_file_path = os.path.join(extract_dir, 'assets', 'channel.conf')with open(channel_file_path, mode='w') as f: 
  13.     f.write(channel)  # 写入渠道号写进去 
  14. os.chdir(extract_dir) 
  15.  
  16. output_file_name = '输出文件名称' 
  17. output_file_path = '输出文件路径' 
  18. output_file_path_tmp = os.path.join(output_dir, output_file_name + '_tmp.apk') 
  19.  
  20. # 压缩 
  21. os.system(ZIP_PATH + ' -r %s *' % output_file_path) 
  22. os.rename(output_file_path, output_file_path_tmp) 
  23.  
  24. # 重新签名 
  25. # jarsigner -sigalg MD5withRSA -digestalg SHA1 -keystore your_keystore_path 
  26. # -storepass your_storepass -signedjar your_signed_apk, your_unsigned_apk, your_alias 
  27. signer_params = ' -verbose -sigalg MD5withRSA -digestalg SHA1' + \ 
  28.           ' -keystore %s -storepass %s %s %s -sigFile CERT' % \      
  29.            ( 
  30.                     sign, # 签名文件路径 
  31.                     store_pass, # 存储密码 
  32.                     output_file_path_tmp, 
  33.                     alias # 别名                 
  34.            ) 
  35.  
  36. os.system(JAR_SIGNER_PATH + signer_params) 
  37.  
  38. # Zip对齐 
  39. os.system(ZIP_ALIGN_PATH + ' -v 4 %s %s' % (output_file_path_tmp, output_file_path)) 
  40. os.remove(output_file_path_tmp)  

在这里,几个PATH分别表示zip、unzip、jarsigner和zipalign这几个可执行文件的路径。

签名是apk的一个重要机制,它给apk里的每一个文件(META-INF目录下的除外)计算一个hash值,记录在META-INF下的若干文件里。Zip对齐能够优化运行时Android读取资源的效率,这一步虽然不是必须的,但还是推荐做一下。

采用这个方法,我们不需要再编译Java代码,速度有极大地提升。大约每10秒就能打一个包。

同时给出读取渠道号的实现代码:

  1. public static String getChannel(Context context) {  
  2.     String channel = ""; 
  3.     InputStream is = null; 
  4.     try {  
  5.         is = context.getAssets().open("channel.conf"); 
  6.         byte[] buffer = new byte[100]; 
  7.         int l = is.read(buffer); 
  8.  
  9.         channel = new String(buffer, 0, l); 
  10.     } catch (IOException e) {  
  11.         // 如果读不到,那么取缺省值 
  12.     } finally {  
  13.         if (is != null) {  
  14.             try {  
  15.                 is.close(); 
  16.             } catch (Exception ignored) {  
  17.             } 
  18.         } 
  19.     } 
  20.     return channel; 
  21. }  

顺便说一下,还可以用aapt这个工具来替代zip&unzip来实现文件替换:

  1. # 替换assets/channel.conf 
  2. os.chdir(base_dir)    
  3. os.system(AAPT_PATH + ' remove %s assets/channel.conf' % output_file_path_tmp)    
  4. os.system(AAPT_PATH + ' add %s assets/channel.conf' % output_file_path_tmp)  

3.美团给出的一种方案

刚才上文提到META-INF目录对签名机制是豁免的,往这里面放东西就可以免去重签名这一步,美团技术团队就是这么做的。

  1. import zipfile 
  2. zipped = zipfile.ZipFile(your_apk, 'a', zipfile.ZIP_DEFLATED) 
  3. empty_channel_file = "META-INF/mtchannel_{ channel}".format(channel=your_channel) 
  4. zipped.write(your_empty_file, empty_channel_file)  

给META-INFO目录加入一个名为“mtchannel_渠道号”的空文件,在Java这边查找到这个文件,取得文件名即可:

  1. public static String getChannel(Context context) {  
  2.     ApplicationInfo appinfo = context.getApplicationInfo(); 
  3.     String sourceDir = appinfo.sourceDir; 
  4.     String ret = ""; 
  5.     ZipFile zipfile = null; 
  6.     try {  
  7.         zipfile = new ZipFile(sourceDir); 
  8.         Enumeration<?> entries = zipfile.entries(); 
  9.         while (entries.hasMoreElements()) {  
  10.             ZipEntry entry = ((ZipEntry) entries.nextElement()); 
  11.             String entryName = entry.getName(); 
  12.             if (entryName.startsWith("mtchannel")) {  
  13.                 ret = entryName; 
  14.                 break; 
  15.             } 
  16.         } 
  17.     } catch (IOException e) {  
  18.         e.printStackTrace(); 
  19.     } finally {  
  20.         if (zipfile != null) {  
  21.             try {  
  22.                 zipfile.close(); 
  23.             } catch (IOException e) {  
  24.                 e.printStackTrace(); 
  25.             } 
  26.         } 
  27.     } 
  28.  
  29.     String[] split = ret.split("_"); 
  30.     if (split != null && split.length >= 2) {  
  31.         return ret.substring(split[0].length() + 1); 
  32.  
  33.     } else {  
  34.         return ""; 
  35.     } 
  36. }  

这个方法省去了重签名这一步,速度提升也很大。他们的描述是“900多个渠道不到一分钟就能打完”,也就是不到0.06s一个包。

4.利用Zip文件comment的终极方案

另外给出了一个终极方案:我们知道Zip文件末尾有一块区域,可以用来存放文件的comment。改动这个区域,丝毫不会影响Zip文件的内容。

打包的代码很简单:

  1. shutil.copyfile(src_file_path, output_file_path) 
  2.  
  3. with zipfile.ZipFile(output_file_path, mode='a') as zipFile: 
  4.      zipFile.comment = bytes(channel, encoding=‘utf8') 

这个方法比前一个方法的区别在于,它不会修改Apk的内容,也就不必重新打包,速度又有提升!

按文档中的说法,这个方法1s内可以打300多个包,也就是说单个包的时间小于10毫秒!

读取的代码稍微复杂一些。

Java 7的ZipFile类,有getComment方法,可以轻易地读取comment值。然而这个方法只在Android 4.4以及更高版本才可用,我们就需要多花点时间把这段逻辑移植过来。所幸这里的逻辑不复杂,我们查看源码,可以看到主要逻辑都在ZipFile的一个私有方法readCentralDir里,一小部分读取二进制数据的逻辑在libcore.io.HeapBufferIterator,全部搬过来,整理一下就搞定了:

  1. public static String getChannel(Context context) {  
  2.    String packagePath = context.getPackageCodePath(); 
  3.  
  4.    RandomAccessFile raf = null; 
  5.    String channel = ""; 
  6.    try {  
  7.       raf = new RandomAccessFile(packagePath, "r"); 
  8.       channel = readChannel(raf); 
  9.    } catch (IOException e) {  
  10.       // ignore 
  11.    } finally {  
  12.       if (raf != null) {  
  13.          try {  
  14.             raf.close(); 
  15.          } catch (IOException e) {  
  16.             // ignore 
  17.          } 
  18.       } 
  19.    } 
  20.  
  21.    return channel;}private static final long LOCSIG = 0x4034b50;private static final long ENDSIG = 0x6054b50;private static final int ENDHDR = 22;private static short peekShort(byte[] src, int offset) {  
  22.    return (short) ((src[offset + 1] << 8) | (src[offset] & 0xff));}private static String readChannel(RandomAccessFile raf) throws IOException {  
  23.    // Scan back, looking for the End Of Central Directory field. If the zip file doesn't 
  24.    // have an overall comment (unrelated to any per-entry comments), we'll hit the EOCD 
  25.    // on the first try. 
  26.    // No need to synchronize raf here -- we only do this when we first open the zip file. 
  27.    long scanOffset = raf.length() - ENDHDR; 
  28.    if (scanOffset < 0) {  
  29.       throw new ZipException("File too short to be a zip file: " + raf.length()); 
  30.    } 
  31.  
  32.    raf.seek(0); 
  33.    final int headerMagic = Integer.reverseBytes(raf.readInt()); 
  34.    if (headerMagic == ENDSIG) {  
  35.       throw new ZipException("Empty zip archive not supported"); 
  36.    } 
  37.    if (headerMagic != LOCSIG) {  
  38.       throw new ZipException("Not a zip archive"); 
  39.    } 
  40.  
  41.    long stopOffset = scanOffset - 65536; 
  42.    if (stopOffset < 0) {  
  43.       stopOffset = 0; 
  44.    } 
  45.  
  46.    while (true) {  
  47.       raf.seek(scanOffset); 
  48.       if (Integer.reverseBytes(raf.readInt()) == ENDSIG) {  
  49.          break; 
  50.       } 
  51.  
  52.       scanOffset--; 
  53.       if (scanOffset < stopOffset) {  
  54.          throw new ZipException("End Of Central Directory signature not found"); 
  55.       } 
  56.    } 
  57.  
  58.    // Read the End Of Central Directory. ENDHDR includes the signature bytes, 
  59.    // which we've already read. 
  60.    byte[] eocd = new byte[ENDHDR - 4]; 
  61.    raf.readFully(eocd); 
  62.  
  63.    // Pull out the information we need. 
  64.    int position = 0; 
  65.    int diskNumber = peekShort(eocd, position) & 0xffff; 
  66.    position += 2; 
  67.    int diskWithCentralDir = peekShort(eocd, position) & 0xffff; 
  68.    position += 2; 
  69.    int numEntries = peekShort(eocd, position) & 0xffff; 
  70.    position += 2; 
  71.    int totalNumEntries = peekShort(eocd, position) & 0xffff; 
  72.    position += 2; 
  73.    position += 4; // Ignore centralDirSize. 
  74.    // long centralDirOffset = ((long) peekInt(eocd, position)) & 0xffffffffL; 
  75.    position += 4; 
  76.    int commentLength = peekShort(eocd, position) & 0xffff; 
  77.    position += 2; 
  78.  
  79.    if (numEntries != totalNumEntries || diskNumber != 0 || diskWithCentralDir != 0) {  
  80.       throw new ZipException("Spanned archives not supported"); 
  81.    } 
  82.  
  83.    String comment = ""; 
  84.    if (commentLength > 0) {  
  85.       byte[] commentBytes = new byte[commentLength]; 
  86.       raf.readFully(commentBytes); 
  87.       comment = new String(commentBytes, 0, commentBytes.length, Charset.forName("UTF-8")); 
  88.    } 
  89.    return comment; 

 需要注意的是,Android 7.0加入了APK Signature Scheme v2技术。在Android Plugin for Gradle 2.2,这一技术是缺省启用的,这会导致第三、第四两种方法打出的包在Android 7.0下面校验失败。解决方法有二,一是把Gradle版本改低,二是在signingConfigs/release下面加上配置v2SigningEnabled false。详细说明见谷歌的文档

总结

用表格说话 

 

责任编辑:庞桂玉 来源: 互联网技术内参 Android渠道打包技术小结

(责任编辑:百科)

    推荐文章
    热点阅读