忽略外部库的proguard配置

iTw*_*nty 10 android proguard gradle android-gradle-plugin

所以,我想在我的项目中添加一个外部库.图书馆本身很小,大约有300种方法.但它配置为非常自由的,它的proguard配置.我在一个准系统项目中使用/不使用库和/不使用proguard运行了一个简单的测试,这就是我想出来的

Proguard    Lib     Method Count
N           N       15631
Y           N       6370
N           Y       15945
Y           Y       15573
Run Code Online (Sandbox Code Playgroud)

如您所见,启用proguard后,计数为~6000.但是当我添加lib时,尽管库本身只有大约300种方法,但计数却达到了大约15000.

所以我的问题是,如何忽略这个特定库的proguard配置?

更新:

现在无法使用android gradle插件.我找到了没有优先权的android bug.请在提及"不可能"时避免回答,并在可能的解决方法或官方决定之前保持问题开启.否则,你将收集一半的赏金而不增加价值.谢谢!

T. *_*art 7

在这种特定情况下,您有几个选择:

  • 从aar中提取classes.jar文件,并将其作为普通jar依赖项包含在项目中(当aar包含资源时不起作用)
  • 更改aar并从中删除使用者proguard规则
  • 使用DexGuard,它允许您过滤掉不需要的消费者规则
  • 做一些gradle hacking,见下文

将以下内容添加到build.gradle:

afterEvaluate {
  // All proguard tasks shall depend on our filter task
  def proguardTasks = tasks.findAll { task ->
    task.name.startsWith('transformClassesAndResourcesWithProguardFor') }
  proguardTasks.each { task -> task.dependsOn filterConsumerRules }
}

// Let's define our custom task that filters some unwanted
// consumer proguard rules
task(filterConsumerRules) << {
  // Collect all consumer rules first
  FileTree allConsumerRules = fileTree(dir: 'build/intermediates/exploded-aar',
                                       include: '**/proguard.txt')

  // Now filter the ones we want to exclude:
  // Change it to fit your needs, replace library with
  // the name of the aar you want to filter.
  FileTree excludeRules = allConsumerRules.matching {
    include '**/library/**'
  }

  // Print some info and delete the file, so ProGuard
  // does not pick it up. We could also just rename it.
  excludeRules.each { File file ->
    println 'Deleting ProGuard consumer rule ' + file
    file.delete()
  }
}
Run Code Online (Sandbox Code Playgroud)

使用DexGuard(7.2.02+)时,您可以将以下代码段添加到build.gradle:

dexguard {
  // Replace library with the name of the aar you want to filter
  // The ** at the end will include every other rule.
  consumerRuleFilter '!**/library/**,**'
}
Run Code Online (Sandbox Code Playgroud)

请注意,逻辑与上面的ProGuard示例相反,consumerRuleFilter将仅包含与模式匹配的消费者规则.

  • “ gradle hacking”方法不适用于Android Studio 2.3+和Android Gradle Plugin 2.3+,因为gradle缓存系统(默认情况下已启用)取代了爆炸的文件夹。 (2认同)