首页 文章

Android:带有Retrofit的库项目导致NoClassDefFoundError

提问于
浏览
0

我正在尝试构建一个Android库项目,该项目使用OkHttp和Retrofit来授予对我们的REST后端的访问权限 .

只要我在 com.squareup.retrofit2:converter-gson 的gradle-dependency上使用 api 而不是 implementation ,它似乎正在工作 . 看来这是唯一需要这个的依赖(所有其他的都可以用 implementation ) .

在这里使用 implementation 时,调用应用程序将与 NoClassDefFoundError 崩溃:

java.lang.NoClassDefFoundError:解析失败:Lcom / google / gson / GsonBuilder;


我正在使用 consumerProguardFiles 和一堆proguard规则文件(例如,一个用于okhttp3,一个用于此repo的retrofit2等) . 然后将所有这些打包到AAR中,因此也应添加依赖项中的规则 .

似乎我错过了 converter-gson 的proguard规则 . 有人可以发布在图书馆项目中使用 com.squareup.retrofit2:converter-gson 所需的规则吗?


编辑1

我的current proguard-rule改造是:

# Retrofit 2.X
## https://square.github.io/retrofit/ ##

-dontwarn retrofit2.**
-keep class retrofit2.** { *; }
-keepattributes Signature
-keepattributes Exceptions

-keepclasseswithmembers class * {
    @retrofit2.http.* <methods>;
}

如上所述,这似乎还不够 . 也许我需要别的东西 converter-gson

编辑2

我的依赖项看起来像这样:

implementation "com.squareup.okhttp3:okhttp:$okHttpVersion"
implementation "com.squareup.retrofit2:retrofit:$retrofitVersion"
api "com.squareup.retrofit2:converter-gson:$retrofitVersion"

而我正试图摆脱最后一个 api 因为我不需要在应用程序中使用这个库(或者这是不可避免的)?


编辑3

嗯,也许proguard是错误的关键字 . 实际上问题在于使用 implementation 而不是 api . 因此,依赖关系不会暴露给消费者 . 见https://stackoverflow.com/a/44493379/2170109 .

但是当我只有库调用 GsonBuilder 时,我不明白为什么我需要向我的库的消费者公开 converter-gson

1 回答

  • 0

    根据官方改装github链接:

    https://github.com/square/retrofit

    Retrofit至少需要Java 7或Android 2.3 .

    如果您使用的是ProGuard,则需要添加以下选项:

    # Retain generic type information for use by reflection by converters and adapters.
    -keepattributes Signature
    # Retain service method parameters.
    -keepclassmembernames,allowobfuscation interface * {
        @retrofit2.http.* <methods>;
    }
    # Ignore annotation used for build tooling.
    -dontwarn org.codehaus.mojo.animal_sniffer.IgnoreJRERequirement
    
    # My personal proguard configuration for ratrofit2
    -dontwarn okio.**
    -dontwarn javax.annotation.**
    -dontwarn retrofit2.Platform$Java8
    

    如果有任何错误,请检查一下您的配置:

    app-> build.gradle

    // retrofit gson
    
    implementation 'com.squareup.retrofit2:retrofit:2.3.0'
    implementation 'com.squareup.retrofit2:converter-gson:2.3.0'
    

    如果有更多错误,您可以共享错误日志以解释您究竟是什么问题 .

相关问题