Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲

ProGuard 入門:輸出檔案說明、常用規則與常見錯誤

編輯:關於 Android 程式設計

開啟 ProGuard 之後專案突然出現上百個 warning 導致建置失敗,是每個 Android 開發者都會遇到的一關。本文整理它的運作方式、四個輸出檔案的用途、一份可直接套用的基礎規則,以及那些錯誤訊息到底在說什麼。

一、如何啟用

在 project.properties(或現行專案的 build.gradle)中加上:

proguard.config=proguard.cfg

Gradle 建置下則是在 release 的 buildTypes 中設定 minifyEnabled true 並指定 proguardFiles。

二、四個輸出檔案

混淆器執行後會在輸出目錄產生四份檔案,各自用途不同:

  • dump.txt:描述 apk 中所有 class 的內部結構,用來確認哪些類別最終被打包進去。
  • mapping.txt:記錄原始名稱與混淆後名稱的對應關係。這份檔案極重要——線上收到的崩潰堆疊都是混淆過的 a.b.c(),必須靠它反譯回可讀的類別與方法名。每次上線版本都要各自保存一份,對錯版本就無法還原。
  • seeds.txt:列出未被混淆的類別與成員,用來確認 keep 規則有沒有生效。
  • usage.txt:列出被移除的程式碼,可以用來檢查是否有「以為會保留但實際被砍掉」的部分。

三、一份實用的基礎規則

# 關閉優化(遇到複雜專案時可先關閉以排除問題)
-dontoptimize

# 保留泛型簽名資訊,否則 Gson/Jackson 這類反射庫會出錯
-keepattributes Signature
-keepattributes *Annotation*

# 保留原始碼行號,讓線上堆疊能對回實際行數
-keepattributes SourceFile,LineNumberTable

# 不要跳過非公開的 library 類別與成員
-dontskipnonpubliclibraryclassmembers
-dontskipnonpubliclibraryclasses

# 明確宣告第三方 JAR 的位置
-libraryjars libs/android-support-v4.jar

# 不混淆第三方套件
-keep class android.support.v4.** { *; }
-dontwarn android.support.v4.**

四、解讀常見錯誤訊息

[proguard] Note: there were 1 references to unknown classes.
[proguard] Warning: there were 269 unresolved references to classes or interfaces.
[proguard] You may need to specify additional library jars (using '-libraryjars'),
[proguard] or perhaps the '-dontskipnonpubliclibraryclasses' option.
[proguard] Warning: there were 57 unresolved references to program class members.
[proguard] Your input classes appear to be inconsistent.
[proguard] You may need to recompile them and try again.
[proguard] Warning: there were 269 unresolved references...
BUILD FAILED
Please correct the above warnings first.

逐條翻譯成人話:

  • unresolved references to classes or interfaces:程式碼中引用了 ProGuard 看不到的類別。通常是缺少 library jars 宣告,或該依賴沒有被正確加入 classpath。
  • unresolved references to program class members:類別找到了,但其中的欄位/方法找不到。多半是版本不一致——jar 與原始碼來自不同版本。
  • input classes appear to be inconsistent:同上,強烈暗示需要重新完整編譯一次(clean build),因為增量編譯留下了過時的 class 檔。

臨時應急可以用 -dontwarn 套件名.** 把警告壓下去,但這只是遮住症狀。正確做法是補上缺的 -libraryjars 或 -keep 規則。

五、哪些東西一定要 keep

這是最實用的一段經驗——凡是「透過名稱被間接存取」的東西,都必須顯式保留:

  • 被序列化的模型類別(Gson、Jackson、Parcelable 的 CREATOR)
  • 在 XML 中由名稱引用的類別:自訂 View、Activity、Fragment、Adapter
  • JNI 中呼叫的類別與方法(native 對應的 Java 端)
  • 透過反射呼叫的建構子與方法
  • Enum 的 values() 與 valueOf()
  • WebView 中透過 addJavascriptInterface 暴露給 JS 的物件

關於「專案引入的第三方 JAR 要不要設定混淆」,答案是:分兩類處理。純第三方(如 support library)建議 -keep 不混淆,因為它們靠名稱反射的內部結構你無法掌握;而自己擁有原始碼、會動態產生 JAR 的模組,通常可以正常混淆,除非其中有上述「靠名稱存取」的設計。

參考資料:Android 官方 ProGuard 說明頁、ProGuard 官方網站,以及 Gson 打包問題的相關討論。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © Android教程網 All Rights Reserved