標籤:android 打包
加入代碼混淆器,主要是加入proguard-project.txt檔案的規則進行混淆,之前建立Android程式是proguard.cfg檔案
可以看一下我採用的通用規則(proguard-project.txt檔案)
-optimizationpasses 5-dontusemixedcaseclassnames-dontskipnonpubliclibraryclasses-dontskipnonpubliclibraryclassmembers-dontpreverify-verbose-optimizations !code/simplification/arithmetic,!field/*,!class/merging/*-keepattributes *Annotation*-renamesourcefileattribute SourceFile-keepattributes SourceFile,LineNumberTable# 以下兩個命令配合讓類的路徑給刪除了-allowaccessmodification-repackageclasses ”# 記錄產生的日誌資料,在 proguard 目錄下-dump class_files.txt-printseeds seeds.txt-printusage unused.txt-printmapping mapping.txt# 異常都可以忽略就開啟#-dontwarn-keep public class * extends android.app.Activity-keep public class * extends android.app.Application-keep public class * extends android.app.Service-keep public class * extends android.content.BroadcastReceiver-keep public class * extends android.content.ContentProvider-keep public class * extends android.app.backup.BackupAgentHelper-keep public class * extends android.preference.Preference-keep public class com.android.vending.licensing.ILicensingService-dontnote com.android.vending.licensing.ILicensingService-keepnames class * implements java.io.Serializable# Explicitly preserve all serialization members. The Serializable interface# is only a marker interface, so it wouldn’t save them.-keepclassmembers class * implements java.io.Serializable {static final long serialVersionUID;private static final java.io.ObjectStreamField[] serialPersistentFields;private void writeObject (java.io.ObjectOutputStream);private void readObject (java.io.ObjectInputStream);java.lang.Object writeReplace ();java.lang.Object readResolve ();}# Preserve all native method names and the names of their classes.#-keepclasseswithmembernames class * {#native ;#}#-keepclasseswithmembernames class * {#public (android.content.Context, android.util.AttributeSet);#}#-keepclasseswithmembernames class * {#public (android.content.Context, android.util.AttributeSet, int);#}# Preserve static fields of inner classes of R classes that might be accessed# through introspection.#-keepclassmembers class **.R$* {#public static ;#}# Preserve the special static methods that are required in all enumeration classes.-keepclassmembers enum * {public static **[] values ();public static ** valueOf (java.lang.String);}-keep class * implements android.os.Parcelable {public static final android.os.Parcelable$Creator *;}# 如果你的工程是對外提供方法調用就開啟#-keep public class * {# public protected *;#}
如果還有規則就加在後面
另外,我們一般需要混淆的是自己寫的代碼,引入的第三方庫檔案是不需要混淆的,否則會出現如下錯誤:
就是找不到所需要的類。所以第三方庫需要指出來不混淆,方法如下:
上面是android.support.v4.×找不到所需類,查看引入庫的包名
在proguard-project.txt後面加上
-dontwarn android.support.v4.** -keep class android.support.v4.** { *; }
第一句是忽略這個警告,第二句是保持類不混淆
把你所有引入的第三方庫弄完後,在project.properties檔案裡加上一句
proguard.config=proguard-project.txt
就可以編譯了(怎麼編譯?)
編譯後,可以在bin裡看到混淆代碼的apk檔案,是不是檔案變小了,多爽!
同時,在bin/proguard檔案夾裡多了幾個檔案
其中,mapping.txt就是所有混淆的類及變數名的前後參照,usage.txt是你在代碼中沒用到的方法,都給你列出來了,是最佳化後的結果。
Android程式加入代碼混淆器