Android jar打包混淆初见

打包

  • build工程,确保Module/build/intermediates/class/{debug | release}/中生成了 .class文件

  • 在Module Gradle中添加task

task jarMyLib(type: Jar, dependsOn: ['build']) {
    archiveName = 'my-lib.jar'
    from('build/intermediates/classes/release')
    destinationDir = file('build/libs')
    exclude('com/XXX/XXX/BuildConfig.class')
    exclude('com/XXX/XXX/BuildConfig\$*.class')
    exclude('**/R.class')
    exclude('**/R\$*.class')
    include('com/XXX/XXX/*.class')
    include('com/XXX/XXX/*/*.class')
}
  • 打开Terminal,输入gradlew jarMyLib,将生成my-lib.jar

混淆

  • 引入@Keep注解
dependencies {
    compile 'com.android.support:support-annotations:23.3.0'
}
  • 代码使用@Keep注解需要保留的类、方法、成员变量、内部类等

  • 编辑proguard-rules.pro文件,添加混淆规则

#不跳过非公共类
-dontskipnonpubliclibraryclasses
#不跳过非公共类的成员
-dontskipnonpubliclibraryclassmembers
#打印配置文件
-printconfiguration
#保留@Keep注解
-keep,allowobfuscation @interface android.support.annotation.Keep
-keep @android.support.annotation.Keep class *
-dontwarn android.support.annotation.Keep
-keepclassmembers class * {
    @android.support.annotation.Keep *;
}
#保留内部类,异常,签名
-keepattributes Exceptions,InnerClasses,Signature
#保留方法参数名
-keepparameternames
#保留注解
-keepattributes *Annotation*
#不裁剪多余代
-dontshrink
#不优化代码
-dontoptimize
#输出所有消息
-verbose
  • 在Module Gradle中添加task
def androidSDKDir = plugins.getPlugin('com.android.library').sdkHandler.getSdkFolder()
def androidJarDir = androidSDKDir.toString() + '/platforms/' + "${android.compileSdkVersion}" + '/android.jar'
task proguardTask(type: ProGuardTask, dependsOn: ['jarMyLib']) {
    // 未混淆的jar
    injars('build/libs/my-lib.jar')
    // 混淆后的jar路径
    outjars('build/libs/progard.jar')
    libraryjars(androidJarDir)
    // 具体需要keep住的类
    configuration 'proguard-rules.pro'
}
  • 打开Terminal,输入gradlew proguardTask,将自动生成混淆后的progard.jar
    原文作者:fengmlo
    原文地址: https://www.jianshu.com/p/c3acba8ba8ba
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞