日韩无码专区无码一级三级片|91人人爱网站中日韩无码电影|厨房大战丰满熟妇|AV高清无码在线免费观看|另类AV日韩少妇熟女|中文日本大黄一级黄色片|色情在线视频免费|亚洲成人特黄a片|黄片wwwav色图欧美|欧亚乱色一区二区三区

RELATEED CONSULTING
相關(guān)咨詢
選擇下列產(chǎn)品馬上在線溝通
服務(wù)時間:8:30-17:00
你可能遇到了下面的問題
關(guān)閉右側(cè)工具欄

新聞中心

這里有您想知道的互聯(lián)網(wǎng)營銷解決方案
Android渠道打包技術(shù)小結(jié)

導(dǎo)讀

10年積累的網(wǎng)站設(shè)計、做網(wǎng)站經(jīng)驗,可以快速應(yīng)對客戶對網(wǎng)站的新想法和需求。提供各種問題對應(yīng)的解決方案。讓選擇我們的客戶得到更好、更有力的網(wǎng)絡(luò)服務(wù)。我雖然不認(rèn)識你,你也不認(rèn)識我。但先建設(shè)網(wǎng)站后付款的網(wǎng)站建設(shè)流程,更有巢湖免費網(wǎng)站建設(shè)讓你可以放心的選擇與我們合作。

本文對比了渠道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.  
  2.      android:name="CHANNEL" 
  3.      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 = '解壓的目標(biāo)目錄路徑' 
  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é)

用表格說話


網(wǎng)站題目:Android渠道打包技術(shù)小結(jié)
文章路徑:http://www.5511xx.com/article/cdohcpp.html