成人免费xxxxx在线视频软件_久久精品久久久_亚洲国产精品久久久_天天色天天色_亚洲人成一区_欧美一级欧美三级在线观看

Android渠道打包技術(shù)小結(jié)

移動開發(fā) Android
與iOS的單一渠道(AppStore)不同,Android平臺在國內(nèi)的渠道多入牛毛。以我們的App為例,就有27個普通渠道(應(yīng)用寶,百度,360這種)和更多的推廣專用渠道。我們打包技術(shù)也經(jīng)過了若干次的改進。

導(dǎo)讀

本文對比了渠道4種渠道打包方式: 

 

 

 

與iOS的單一渠道(AppStore)不同,Android平臺在國內(nèi)的渠道多入牛毛。以我們的App為例,就有27個普通渠道(應(yīng)用寶,百度,360這種)和更多的推廣專用渠道。我們打包技術(shù)也經(jīng)過了若干次的改進。

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. <!-- 自用渠道號設(shè)置 --> 
  2. <meta-data 
  3.      android:name="CHANNEL" 
  4.      android:value="${CHANNEL}”/>  

原理很簡單,gradle編譯的時候,會根據(jù)這個配置,把manifest里對應(yīng)的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. }    

這個辦法,缺點很明顯,每打一個渠道包都會完整得執(zhí)行一遍apk的編譯打包流程,非常慢。近30個包要打一個多小時…優(yōu)點就是不依賴其他工具,gradle自己就能搞定。

2.替換Assets資源打包

assets用于存放一些資源。不同與res,assets里的資源編譯時原樣保留,不需要生成什么resouce id之類的東西。因此,我們可以通過替換assets里的文件打出不同的渠道包,而不用每次都重新編譯。

我們知道apk本質(zhì)上就是個zip文件,那么我們就可以通過解壓縮->替換文件->壓縮的辦法來搞定:

這里給出一份Python3的實現(xiàn)

  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這幾個可執(zhí)行文件的路徑。

簽名是apk的一個重要機制,它給apk里的每一個文件(META-INF目錄下的除外)計算一個hash值,記錄在META-INF下的若干文件里。Zip對齊能夠優(yōu)化運行時Android讀取資源的效率,這一步雖然不是必須的,但還是推薦做一下。

采用這個方法,我們不需要再編譯Java代碼,速度有極大地提升。大約每10秒就能打一個包。

同時給出讀取渠道號的實現(xiàn)代碼:

  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來實現(xiàn)文件替換:

  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目錄對簽名機制是豁免的,往這里面放東西就可以免去重簽名這一步,美團技術(shù)團隊就是這么做的。

  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文件末尾有一塊區(qū)域,可以用來存放文件的comment。改動這個區(qū)域,絲毫不會影響Zip文件的內(nèi)容。

打包的代碼很簡單:

  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') 

這個方法比前一個方法的區(qū)別在于,它不會修改Apk的內(nèi)容,也就不必重新打包,速度又有提升!

按文檔中的說法,這個方法1s內(nèi)可以打300多個包,也就是說單個包的時間小于10毫秒!

讀取的代碼稍微復(fù)雜一些。

Java 7的ZipFile類,有g(shù)etComment方法,可以輕易地讀取comment值。然而這個方法只在Android 4.4以及更高版本才可用,我們就需要多花點時間把這段邏輯移植過來。所幸這里的邏輯不復(fù)雜,我們查看源碼,可以看到主要邏輯都在ZipFile的一個私有方法readCentralDir里,一小部分讀取二進制數(shù)據(jù)的邏輯在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技術(shù)。在Android Plugin for Gradle 2.2,這一技術(shù)是缺省啟用的,這會導(dǎo)致第三、第四兩種方法打出的包在Android 7.0下面校驗失敗。解決方法有二,一是把Gradle版本改低,二是在signingConfigs/release下面加上配置v2SigningEnabled false。詳細說明見谷歌的文檔

總結(jié)

用表格說話 

 

責任編輯:龐桂玉 來源: 互聯(lián)網(wǎng)技術(shù)內(nèi)參
相關(guān)推薦

2022-09-02 15:35:37

Android實踐

2016-12-14 15:13:30

GradleAndroid定制化打包

2019-05-21 14:22:28

Android渠道統(tǒng)計打包

2013-05-29 10:17:56

Hadoop分布式文件系統(tǒng)

2010-09-16 13:36:52

無線網(wǎng)絡(luò)技術(shù)

2012-01-09 14:17:44

Android應(yīng)用商店

2014-01-08 13:13:41

App Builder輕應(yīng)用

2012-04-26 22:51:23

Android

2009-10-28 13:45:00

遠程接入技術(shù)

2014-12-22 10:03:13

2011-04-25 11:40:52

銳捷渠道策略產(chǎn)品技術(shù)

2018-10-29 09:08:02

2022-12-31 09:32:15

AndroidException錯誤

2011-03-01 16:23:37

博科太網(wǎng)結(jié)構(gòu)技術(shù)

2014-07-11 16:46:54

華為

2015-08-19 09:53:17

技術(shù)電商創(chuàng)業(yè)

2011-11-25 10:27:15

2014-08-26 17:12:31

聯(lián)絡(luò)中心Aspect

2011-07-15 11:17:18

寶通英特爾服務(wù)器

2011-07-04 09:16:31

點贊
收藏

51CTO技術(shù)棧公眾號

主站蜘蛛池模板: 日韩中文字幕一区二区 | 国产成人在线视频播放 | 欧美日韩精品一区二区三区蜜桃 | 91精品一区 | 日本黄色短片 | 久青草影院 | 黄a免费网络 | 国产精品伦理一区二区三区 | 久久久久久女 | 秋霞性生活 | 国产亚洲高清视频 | 久久久久中文字幕 | 亚洲乱码一区二区三区在线观看 | av在线一区二区三区 | 91精品国产91久久久久福利 | 国产欧美日韩在线一区 | 国产一区二区自拍 | 亚洲444kkkk在线观看最新 | 日韩成人av在线 | 91精品中文字幕一区二区三区 | 欧美日韩一卡二卡 | 精品99在线| 亚洲一区二区三区在线播放 | 在线国产一区 | 国产精品成人品 | 国产成人啪免费观看软件 | 久久久这里都是精品 | 久久99视频免费观看 | 国产女人与拘做受视频 | 亚洲精品乱码久久久久久久久 | 玖草资源| 久久激情视频 | 玖玖视频免费 | 久久夜色精品国产 | 国产在线观看一区二区 | 精品一二区 | 毛片一级电影 | 国产精品美女久久久 | 中文字幕av亚洲精品一部二部 | 国产在线视频在线观看 | 欧美色视频免费 |