【问题标题】:Proguard not keeping classes when building aarProguard 在构建 aar 时不保留课程
【发布时间】:2018-01-02 20:22:37
【问题描述】:

来自此参考:

https://github.com/codepath/android_guides/wiki/Building-your-own-Android-library

我有以下 gradle 文件:

android {
    compileSdkVersion 25
    buildToolsVersion "26.0.2"

    buildTypes {
        release {
            minifyEnabled true
            consumerProguardFiles 'consumer-proguard-rules.pro'
        }
    }
}

还有以下proguard文件:

-dontobfuscate
-optimizations !code/allocation/variable

-keep public class * {
    public protected *;
}

但是,当我运行“assembleRelease”任务来构建我的发布 aar 文件时,我在 aar 中的所有类都丢失了。

有什么想法吗?

【问题讨论】:

  • 分享你的consumer-proguard-rules.pro
  • 这是我的 consumer-proguard-rules.pro 文件
  • @lostintranslation 请参阅以下对您的 proguard 规则的更正。

标签: android android-proguard aar


【解决方案1】:

您应该将minifyEnabled 设置为false(默认值): consumerProguardFiles 不用于立即缩小(即在构建库本身时)。它在构建库的使用者(例如应用程序)时使用。

不建议在使用之前缩小库,因为在最终构建之前您无法知道实际会使用哪些部分。图书馆通常不这样做。例如LeakCanaryACRAButter Knife

【讨论】:

  • 我试图关注这样的事情。 medium.com/google-developers/… 如果我将 minify 设置为 false,proguard 还会运行吗?
  • 不是立即,如果 consumer 选择执行它(使用它自己的minifyEnabled),proguard 将运行。如果是这样,您的consumer-proguard-rules.pro 将被合并并应用
【解决方案2】:

一般来说,库必须保留操作它所需的所有方法和方法名;例如:

-verbose

# -libraryjars ../app/libs
# -dontpreverify
# -dontobfuscate
# -dontshrink
# -dontoptimize

# keep class BuildConfig
-keep public class **.BuildConfig { *; }

# keep class members of R
-keepclassmembers class **.R$* {public static <fields>;}

问题的答案应该是:

# keep all public and protected method names,
# which could be used by Java reflection.
-keepclassmembernames class * {
    public protected <methods>;
}

很可能还需要更多规则,而-verbose 标志告诉人们在其中写入什么。在针对其他代码构建库时(如上所述),仍然需要为库添加或多或少相同的规则。还有相当多的非开源库具有混淆的类名。

图书馆的build.gradle 可能看起来像这样:

android {
    defaultConfig {
        consumerProguardFiles 'proguard-consumer-rules.pro' 
    }
    buildTypes {
        release {
            minifyEnabled false // don't proguard the library itself.
        }
    }
}

默认proguard-consumer-rules.pro 解释它:

Android Gradle 插件允许定义嵌入到 AAR 中的 ProGuard 规则。

当消费者应用将 minifyEnabled 设置为 true 时,会自动应用这些 ProGuard 规则。

必须使用 build.gradle 文件中的“consumerProguardFiles”属性定义自定义规则文件。

当一个库本身没有被处理时,它仍然可以带来它的 ProGuard 规则——以便在构建整个项目时被使用。

【讨论】:

    【解决方案3】:

    我没有得到你真正想要做的事情,但我可以建议你不要做 assembleRelease 而是在你的另一个项目中导入,清理项目并构建然后使用生成的 aar 来自/build/outputs/aar/ 目录。 并且必须检查你没有在任何地方使用混淆类的引用。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-05-02
      • 2020-04-23
      • 1970-01-01
      • 1970-01-01
      • 2013-03-25
      相关资源
      最近更新 更多