Android渠道打包技術小結

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

1、利用Gradle Product Favor打包

Product Favor是Gradle的自帶的功能,配置很容易:

android {
    productFlavors {
        base {
            manifestPlaceholders = [ CHANNEL:”0"]
        }
        yingyongbao {
            manifestPlaceholders = [ CHANNEL:"1" ]
        }
        baidu {
            manifestPlaceholders = [ CHANNEL:"2"]
        }
    }
}

AndroidManifest.xml

<!-- 自用渠道號設置 -->
<meta-data
     android:name="CHANNEL"
     android:value="${CHANNEL}”/>

原理很簡單,gradle編譯的時候,會根據這個配置,把manifest里對應的metadata占位符替換成指定的值。然后Android這邊在運行期再去取出來就是:

public static String getChannel(Context context) {
    String channel = "";
    PackageManager pm = sContext.getPackageManager();
    try {
        ApplicationInfo ai = pm.getApplicationInfo(
            context.getPackageName(),
            PackageManager.GET_META_DATA);

        String value = ai.metaData.getString("CHANNEL");
        if (value != null) {
            channel = value;
        }
    } catch (Exception e) {
        // 忽略找不到包信息的異常
    }
    return channel;
}

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

2、替換Assets資源打包

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

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

這里給出一份Python3的實現

# 解壓縮
src_file_path = '原始apk文件路徑'
extract_dir = '解壓的目標目錄路徑'
os.makedirs(extract_dir, exist_ok=True)

os.system(UNZIP_PATH + ' -o -d %s %s' % (extract_dir, src_file_path))

# 刪除簽名信息
shutil.rmtree(os.path.join(extract_dir, 'META-INF'))

# 寫入渠道文件assets/channel.conf
channel_file_path = os.path.join(extract_dir, 'assets', 'channel.conf')
with open(channel_file_path, mode='w') as f:
    f.write(channel)  # 寫入渠道號寫進去

os.chdir(extract_dir)

output_file_name = '輸出文件名稱'
output_file_path = '輸出文件路徑'
output_file_path_tmp = os.path.join(output_dir, output_file_name + '_tmp.apk')

# 壓縮
os.system(ZIP_PATH + ' -r %s *' % output_file_path)
os.rename(output_file_path, output_file_path_tmp)

# 重新簽名
# jarsigner -sigalg MD5withRSA -digestalg SHA1 -keystore your_keystore_path
# -storepass your_storepass -signedjar your_signed_apk, your_unsigned_apk, your_alias
signer_params = ' -verbose -sigalg MD5withRSA -digestalg SHA1' + \
                ' -keystore %s -storepass %s %s %s -sigFile CERT' % \
                (
                    sign, # 簽名文件路徑
                    store_pass, # 存儲密碼
                    output_file_path_tmp,
                    alias # 別名
                )

os.system(JAR_SIGNER_PATH + signer_params)

# Zip對齊
os.system(ZIP_ALIGN_PATH + ' -v 4 %s %s' % (output_file_path_tmp, output_file_path))
os.remove(output_file_path_tmp)

在這里,幾個PATH分別表示zip、unzip、jarsigner和zipalign這幾個可執行文件的路徑。

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

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

同時給出讀取渠道號的實現代碼:

public static String getChannel(Context context) {
    String channel = "";
    InputStream is = null;
    try {
        is = context.getAssets().open("channel.conf");
        byte[] buffer = new byte[100];
        int l = is.read(buffer);

        channel = new String(buffer, 0, l);
    } catch (IOException e) {
        // 如果讀不到,那么取缺省值
    } finally {
        if (is != null) {
            try {
                is.close();
            } catch (Exception ignored) {
            }
        }
    }
    return channel;
}

順便說一下,還可以用aapt這個工具來替代zip&unzip來實現文件替換:

# 替換assets/channel.conf
os.chdir(base_dir)
os.system(AAPT_PATH + ' remove %s assets/channel.conf' % output_file_path_tmp)
os.system(AAPT_PATH + ' add %s assets/channel.conf' % output_file_path_tmp)

3、美團給出的一種方案

剛才上文提到META-INF目錄對簽名機制是豁免的,往這里面放東西就可以免去重簽名這一步,美團技術團隊就是這么做的。

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

給META-INFO目錄加入一個名為“mtchannel_渠道號”的空文件,在Java這邊查找到這個文件,取得文件名即可:

public static String getChannel(Context context) {
    ApplicationInfo appinfo = context.getApplicationInfo();
    String sourceDir = appinfo.sourceDir;
    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("mtchannel")) {
                ret = entryName;
                break;
            }
        }
    } catch (IOException e) {
        e.printStackTrace();
    } finally {
        if (zipfile != null) {
            try {
                zipfile.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    String[] split = ret.split("_");
    if (split != null && split.length >= 2) {
        return ret.substring(split[0].length() + 1);

    } else {
        return "";
    }
}

這個方法省去了重簽名這一步,速度提升也很大。他們的描述是“900多個渠道不到一分鐘就能打完”,也就是不到0.06s一個包。

4、利用Zip文件comment的終極方案

另外給出了一個終極方案:
我們知道Zip文件末尾有一塊區域,可以用來存放文件的comment。改動這個區域,絲毫不會影響Zip文件的內容。

打包的代碼很簡單:

shutil.copyfile(src_file_path, output_file_path)

with zipfile.ZipFile(output_file_path, mode='a') as zipFile:
    zipFile.comment = bytes(channel, encoding=‘utf8')

這個方法比前一個方法的區別在于,它不會修改Apk的內容,也就不必重新打包,速度又有提升!
按文檔中的說法,這個方法1s內可以打300多個包,也就是說單個包的時間小于10毫秒!

讀取的代碼稍微復雜一些。
Java 7的ZipFile類,有getComment方法,可以輕易地讀取comment值。然而這個方法只在Android 4.4以及更高版本才可用,我們就需要多花點時間把這段邏輯移植過來。
所幸這里的邏輯不復雜,我們查看源碼,可以看到主要邏輯都在ZipFile的一個私有方法readCentralDir里,一小部分讀取二進制數據的邏輯在libcore.io.HeapBufferIterator,全部搬過來,整理一下就搞定了:

public static String getChannel(Context context) {
   String packagePath = context.getPackageCodePath();

   RandomAccessFile raf = null;
   String channel = "";
   try {
      raf = new RandomAccessFile(packagePath, "r");
      channel = readChannel(raf);
   } catch (IOException e) {
      // ignore
   } finally {
      if (raf != null) {
         try {
            raf.close();
         } catch (IOException e) {
            // ignore
         }
      }
   }

   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) {
   return (short) ((src[offset + 1] << 8) | (src[offset] & 0xff));
}

private static String readChannel(RandomAccessFile raf) throws IOException {
   // Scan back, looking for the End Of Central Directory field. If the zip file doesn't
   // have an overall comment (unrelated to any per-entry comments), we'll hit the EOCD
   // on the first try.
   // No need to synchronize raf here -- we only do this when we first open the zip file.
   long scanOffset = raf.length() - ENDHDR;
   if (scanOffset < 0) {
      throw new ZipException("File too short to be a zip file: " + raf.length());
   }

   raf.seek(0);
   final int headerMagic = Integer.reverseBytes(raf.readInt());
   if (headerMagic == ENDSIG) {
      throw new ZipException("Empty zip archive not supported");
   }
   if (headerMagic != LOCSIG) {
      throw new ZipException("Not a zip archive");
   }

   long stopOffset = scanOffset - 65536;
   if (stopOffset < 0) {
      stopOffset = 0;
   }

   while (true) {
      raf.seek(scanOffset);
      if (Integer.reverseBytes(raf.readInt()) == ENDSIG) {
         break;
      }

      scanOffset--;
      if (scanOffset < stopOffset) {
         throw new ZipException("End Of Central Directory signature not found");
      }
   }

   // Read the End Of Central Directory. ENDHDR includes the signature bytes,
   // which we've already read.
   byte[] eocd = new byte[ENDHDR - 4];
   raf.readFully(eocd);

   // Pull out the information we need.
   int position = 0;
   int diskNumber = peekShort(eocd, position) & 0xffff;
   position += 2;
   int diskWithCentralDir = peekShort(eocd, position) & 0xffff;
   position += 2;
   int numEntries = peekShort(eocd, position) & 0xffff;
   position += 2;
   int totalNumEntries = peekShort(eocd, position) & 0xffff;
   position += 2;
   position += 4; // Ignore centralDirSize.
   // long centralDirOffset = ((long) peekInt(eocd, position)) & 0xffffffffL;
   position += 4;
   int commentLength = peekShort(eocd, position) & 0xffff;
   position += 2;

   if (numEntries != totalNumEntries || diskNumber != 0 || diskWithCentralDir != 0) {
      throw new ZipException("Spanned archives not supported");
   }

   String comment = "";
   if (commentLength > 0) {
      byte[] commentBytes = new byte[commentLength];
      raf.readFully(commentBytes);
      comment = new String(commentBytes, 0, commentBytes.length, Charset.forName("UTF-8"));
   }
   return comment;
}

需要注意的是,Android 7.0加入了APK Signature Scheme v2技術。在Android Plugin for Gradle 2.2,這一技術是缺省啟用的,這會導致第三、第四兩種方法打出的包在Android 7.0下面校驗失敗。解決方法有二,一是把Gradle版本改低,二是在signingConfigs/release下面加上配置v2SigningEnabled false。詳細說明見谷歌的文檔

總結

用表格說話

是否需要重新編譯 是否需要壓縮/解壓縮 是否需要重新簽名 是否需要重新Zipalign 平均耗時
利用Gradle Product Favor打包 ? ? ? ? 超過2分鐘
替換Assets資源打包 ? ? ? ? 約10秒
META-INF加入空文件 ? ? ? 不確定 約0.05秒
利用Zip的Comment打包 ? ? ? ? 少于0.01秒
最后編輯于
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。
  • 序言:七十年代末,一起剝皮案震驚了整個濱河市,隨后出現的幾起案子,更是在濱河造成了極大的恐慌,老刑警劉巖,帶你破解...
    沈念sama閱讀 228,119評論 6 531
  • 序言:濱河連續發生了三起死亡事件,死亡現場離奇詭異,居然都是意外死亡,警方通過查閱死者的電腦和手機,發現死者居然都...
    沈念sama閱讀 98,382評論 3 415
  • 文/潘曉璐 我一進店門,熙熙樓的掌柜王于貴愁眉苦臉地迎上來,“玉大人,你說我怎么就攤上這事?!?“怎么了?”我有些...
    開封第一講書人閱讀 176,038評論 0 373
  • 文/不壞的土叔 我叫張陵,是天一觀的道長。 經常有香客問我,道長,這世上最難降的妖魔是什么? 我笑而不...
    開封第一講書人閱讀 62,853評論 1 309
  • 正文 為了忘掉前任,我火速辦了婚禮,結果婚禮上,老公的妹妹穿的比我還像新娘。我一直安慰自己,他們只是感情好,可當我...
    茶點故事閱讀 71,616評論 6 408
  • 文/花漫 我一把揭開白布。 她就那樣靜靜地躺著,像睡著了一般。 火紅的嫁衣襯著肌膚如雪。 梳的紋絲不亂的頭發上,一...
    開封第一講書人閱讀 55,112評論 1 323
  • 那天,我揣著相機與錄音,去河邊找鬼。 笑死,一個胖子當著我的面吹牛,可吹牛的內容都是我干的。 我是一名探鬼主播,決...
    沈念sama閱讀 43,192評論 3 441
  • 文/蒼蘭香墨 我猛地睜開眼,長吁一口氣:“原來是場噩夢啊……” “哼!你這毒婦竟也來了?” 一聲冷哼從身側響起,我...
    開封第一講書人閱讀 42,355評論 0 288
  • 序言:老撾萬榮一對情侶失蹤,失蹤者是張志新(化名)和其女友劉穎,沒想到半個月后,有當地人在樹林里發現了一具尸體,經...
    沈念sama閱讀 48,869評論 1 334
  • 正文 獨居荒郊野嶺守林人離奇死亡,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內容為張勛視角 年9月15日...
    茶點故事閱讀 40,727評論 3 354
  • 正文 我和宋清朗相戀三年,在試婚紗的時候發現自己被綠了。 大學時的朋友給我發了我未婚夫和他白月光在一起吃飯的照片。...
    茶點故事閱讀 42,928評論 1 369
  • 序言:一個原本活蹦亂跳的男人離奇死亡,死狀恐怖,靈堂內的尸體忽然破棺而出,到底是詐尸還是另有隱情,我是刑警寧澤,帶...
    沈念sama閱讀 38,467評論 5 358
  • 正文 年R本政府宣布,位于F島的核電站,受9級特大地震影響,放射性物質發生泄漏。R本人自食惡果不足惜,卻給世界環境...
    茶點故事閱讀 44,165評論 3 347
  • 文/蒙蒙 一、第九天 我趴在偏房一處隱蔽的房頂上張望。 院中可真熱鬧,春花似錦、人聲如沸。這莊子的主人今日做“春日...
    開封第一講書人閱讀 34,570評論 0 26
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽。三九已至,卻和暖如春,著一層夾襖步出監牢的瞬間,已是汗流浹背。 一陣腳步聲響...
    開封第一講書人閱讀 35,813評論 1 282
  • 我被黑心中介騙來泰國打工, 沒想到剛下飛機就差點兒被人妖公主榨干…… 1. 我叫王不留,地道東北人。 一個月前我還...
    沈念sama閱讀 51,585評論 3 390
  • 正文 我出身青樓,卻偏偏與公主長得像,于是被迫代替她去往敵國和親。 傳聞我的和親對象是個殘疾皇子,可洞房花燭夜當晚...
    茶點故事閱讀 47,892評論 2 372

推薦閱讀更多精彩內容

  • Android 自定義View的各種姿勢1 Activity的顯示之ViewRootImpl詳解 Activity...
    passiontim閱讀 172,618評論 25 708
  • [TOC] 打包流程 前言 我們每一個產品中一般都是由一位同事來負責打包工作的,其他同學一般是不需要關心具體的流程...
    鐘金寶閱讀 1,639評論 0 5
  • Android市場的渠道分散已不是什么新鮮事,但如何高效打包仍是令許多開發者頭疼的問題。本篇文章著重介紹了目前最新...
    _曾胖子閱讀 1,940評論 1 10
  • 迪士尼樂園,第二次來了。 第一次是公司活動,這一次是陪琦琦玩。 童話的世界,角角落落。人群攢動,排隊,排隊,換取游...
    LOVE玲媛閱讀 370評論 0 0
  • 一個人的豁達,體現在落魄的時候。 一個人的涵養,體現在憤怒的時候。 一個人的體貼,體現在悲傷的時候。 一個人的成熟...
    北京無極堂閱讀 277評論 0 0