標籤:
現在Android多渠道打包普遍使用的是gradle設定productFlavor方式,通過gradle aR,可以執行一個命令,打出多個包,但是這種方式每次都要走一遍打包流程,而目前很多包僅僅是渠道號不一致,並不需要重新在走一遍編譯,打包流程。
看了美團的解決方案,他們利用了簽名的漏洞,在META-INF目錄內添加空檔案,可以不用重新簽名應用,本文介紹了一種使用者執行過gradle aR命令,自動運行渠道包產生指令碼,打多個渠道包的方式。想要入門gradle指令碼,請查看鄧凡平大神的部落格文章:http://blog.csdn.net/innost/article/details/48228651 。
以下是打包指令碼:
apply plugin: ‘com.android.application‘def versionNameString="1.0"def versionCodeInt=1def appName="打包測試" //你的應用的名稱def releaseApk=‘app/build/outputs/apk/app-release.apk‘def packageChannel(String versionName,String appName,String releaseApk){ try { def stdout = new ByteArrayOutputStream() exec { //執行Python指令碼 commandLine ‘python‘,rootProject.getRootDir().getAbsolutePath()+"/app/mulit_channel.py",versionName,appName,releaseApk standardOutput = stdout } return stdout.toString().trim() } catch (ignored) { return "UnKnown"; }}android { compileSdkVersion 22 buildToolsVersion "22.0.1" defaultConfig { applicationId "com.ndktest" minSdkVersion 14 targetSdkVersion 22 versionCode versionCodeInt versionName versionNameString } signingConfigs { debug { // No debug config } release { storeFile file("../keystore/netstars.keystore") storePassword "123456" keyAlias "netstars.keystore" keyPassword "123456" } } buildTypes { release { buildConfigField "boolean", "LOG_DEBUG", "false" minifyEnabled true zipAlignEnabled true // 移除無用的resource檔案 shrinkResources true signingConfig signingConfigs.release proguardFiles getDefaultProguardFile(‘proguard-android.txt‘), ‘proguard-rules.pro‘ } debug { minifyEnabled false debuggable true } } sourceSets { main { jniLibs.srcDirs = [‘libs‘] } } project.afterEvaluate { //在Release執行以後 tasks.getByName("assembleRelease"){ it.doLast{ def rApk=new File(releaseApk); if(rApk.exists()){ packageChannel(versionNameString,appName,rApk.absolutePath) } } } }}dependencies { compile fileTree(dir: ‘libs‘, include: [‘*.jar‘]) compile ‘com.android.support:appcompat-v7:22.2.0‘}
Python指令碼:
#!/usr/bin/python# coding=utf-8import zipfileimport shutilimport osimport datetimeimport sys# 空檔案 便於寫入此空檔案到apk包中作為channel檔案src_empty_file = ‘empty.txt‘# 建立一個空檔案(不存在則建立)f = open(src_empty_file, ‘w‘)f.close()# 擷取渠道列表channel_file = ‘channel.txt‘f = open(channel_file)lines = f.readlines()f.close()src_apk=sys.argv[3]# file name (with extension)src_apk_file_name = os.path.basename(src_apk)print(src_apk_file_name)# 分割檔案名稱與尾碼temp_list = os.path.splitext(src_apk_file_name)# name without extensionsrc_apk_name = temp_list[0]# 尾碼名,包含. 例如: ".apk "src_apk_extension = temp_list[1]# 建立組建目錄,與檔案名稱相關output_dir = ‘../output‘ + ‘/‘# 目錄不存在則建立if not os.path.exists(output_dir): os.mkdir(output_dir)# 遍曆渠道號並建立對應渠道號的apk檔案for line in lines: # 擷取當前渠道號,因為從渠道檔案中獲得帶有\n,所有strip一下 target_channel = line.strip() #擷取日期 now = datetime.datetime.now() nowTime=now.strftime(‘%Y-%m-%d‘) # 拼接對應渠道號的apk length=len(sys.argv) if length>1 : target_apk = output_dir +sys.argv[2]+"v"+sys.argv[1]+"_"+nowTime+ "_" + target_channel + src_apk_extension else: target_apk = output_dir +src_apk_name + "_" + target_channel + src_apk_extension # 拷貝建立新apk shutil.copy(src_apk, target_apk) # zip擷取建立立的apk檔案 zipped = zipfile.ZipFile(target_apk, ‘a‘, zipfile.ZIP_DEFLATED) # 初始化渠道資訊 empty_channel_file = "META-INF/channel_{channel}".format(channel = target_channel) # 寫入渠道資訊 zipped.write(src_empty_file, empty_channel_file) # 關閉zip流 zipped.close()
1.擷取到渠道號:
import android.content.Context;import android.content.SharedPreferences;import android.content.SharedPreferences.Editor;import android.content.pm.ApplicationInfo;import android.content.pm.PackageManager.NameNotFoundException;import android.preference.PreferenceManager;import android.text.TextUtils;import java.io.IOException;import java.util.Enumeration;import java.util.zip.ZipEntry;import java.util.zip.ZipFile; /*** *https://github.com/GavinCT/AndroidMultiChannelBuildTool ***/public class ChannelUtil { private static final String CHANNEL_KEY = "channel"; private static final String CHANNEL_VERSION_KEY = "channel_version"; private static String mChannel; /** * 返回市場。 如果擷取失敗返回"" * @param context * @return */ public static String getChannel(Context context){ return getChannel(context, ""); } /** * 返回市場。 如果擷取失敗返回defaultChannel * @param context * @param defaultChannel * @return */ public static String getChannel(Context context, String defaultChannel) { //記憶體中擷取 if(!TextUtils.isEmpty(mChannel)){ return mChannel; } //sp中擷取 mChannel = getChannelBySharedPreferences(context); if(!TextUtils.isEmpty(mChannel)){ return mChannel; } //從apk中擷取 mChannel = getChannelFromApk(context, CHANNEL_KEY); if(!TextUtils.isEmpty(mChannel)){ //儲存sp中備用 saveChannelBySharedPreferences(context, mChannel); return mChannel; } //全部擷取失敗 return defaultChannel; } /** * 從apk中擷取版本資訊 * @param context * @param channelKey * @return */ private static String getChannelFromApk(Context context, String channelKey) { //從apk包中擷取 ApplicationInfo appinfo = context.getApplicationInfo(); String sourceDir = appinfo.sourceDir; //預設放在meta-inf/裡, 所以需要再拼接一下 String key = "META-INF/" + channelKey; 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(key)) { ret = entryName; break; } } } catch (IOException e) { e.printStackTrace(); } finally { if (zipfile != null) { try { zipfile.close(); } catch (IOException e) { e.printStackTrace(); } } } String[] split = ret.split("_"); String channel = ""; if (split != null && split.length >= 2) { channel = ret.substring(split[0].length() + 1); } return channel; } /** * 本地儲存channel & 對應版本號碼 * @param context * @param channel */ private static void saveChannelBySharedPreferences(Context context, String channel){ SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(context); Editor editor = sp.edit(); editor.putString(CHANNEL_KEY, channel); editor.putInt(CHANNEL_VERSION_KEY, getVersionCode(context)); editor.commit(); } /** * 從sp中擷取channel * @param context * @return 為空白表示擷取異常、sp中的值已經失效、sp中沒有此值 */ private static String getChannelBySharedPreferences(Context context){ SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(context); int currentVersionCode = getVersionCode(context); if(currentVersionCode == -1){ //擷取錯誤 return ""; } int versionCodeSaved = sp.getInt(CHANNEL_VERSION_KEY, -1); if(versionCodeSaved == -1){ //本地沒有儲存的channel對應的版本號碼 //第一次使用 或者 原先儲存版本號碼異常 return ""; } if(currentVersionCode != versionCodeSaved){ return ""; } return sp.getString(CHANNEL_KEY, ""); } /** * 從包資訊中擷取版本號碼 * @param context * @return */ private static int getVersionCode(Context context){ try{ return context.getPackageManager().getPackageInfo(context.getPackageName(), 0).versionCode; }catch(NameNotFoundException e) { e.printStackTrace(); } return -1; }}
友盟SDK中提供了通過代碼設定渠道號的功能,結合上述打包指令碼和擷取指令碼資訊代碼,相信多渠道打包問題基本可以得到解決了。
項目Demo:http://git.oschina.net/fengcunhan/AndroidMulitChannel
Android 多渠道打包