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秒
最后編輯于
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。

推薦閱讀更多精彩內容

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