如何解决多个 D8 警告:<Class X> 未找到,默认或静态接口方法 desugaring <Class Y> 需要它?

How to resolve multiple D8 warnings: <Class X> was not found, it is required for default or static interface methods desugaring <Class Y>?

从 3.1.4 升级到 Android Gradle 插件后。2.x 我收到多个警告,例如:

D8: Type `com.google.gson.reflect.TypeToken` was not found, it is required for default or static interface methods desugaring of `com.google.gson.reflect.TypeToken org.springframework.http.converter.json.GsonHttpMessageConverter.getTypeToken(java.lang.reflect.Type)`
D8: Type `com.squareup.okhttp.MediaType` was not found, it is required for default or static interface methods desugaring of `com.squareup.okhttp.MediaType org.springframework.http.client.OkHttpClientHttpRequest.getContentType(org.springframework.http.HttpHeaders)`
D8: Type `org.apache.http.impl.client.HttpClients` was not found, it is required for default or static interface methods desugaring of `void org.springframework.http.client.HttpComponentsClientHttpRequestFactory.<init>()`
D8: Interface `org.apache.http.HttpEntity` not found. It's needed to make sure desugaring of `org.springframework.http.client.HttpComponentsStreamingClientHttpRequest$StreamingHttpEntity` is correct. Desugaring will assume that this interface has no default method.
D8: Type `org.conscrypt.Conscrypt` was not found, it is required for default or static interface methods desugaring of `okhttp3.internal.platform.Platform okhttp3.internal.platform.ConscryptPlatform.buildIfSupported()`
...

项目正在使用 Java 1.8 源兼容性 (lambdas),看起来警告来自 Android gradle class dexer,它已默认启用AGP 3.2.0.

  1. 我试图用以下几行在 proguard-rules.pro 中抑制这些警告,但似乎没有任何效果。

    -dontwarn com.google.gson.reflect.TypeToken
    -keep class com.google.gson.reflect.TypeToken { *; }
    -dontwarn org.apache.http.**
    -keep class com.squareup.okhttp.** { *; }
    -dontwarn com.squareup.okhttp.**
    -keep class org.springframework.http.client.** { *; }
    -dontwarn org.springframework.http.client.**
    
  2. 让警告消失的唯一方法是在 build.gradle 文件中将 minifyEnableduseProguard 设置为 false

  3. 我尝试了 AGP 3.3.0-alpha13 和新的 AGP 3.2.1 但没有成功。

您可以使用 https://github.com/mdawid/D8WarningTest

中的示例项目克隆存储库

更新:问题已在 Android Gradle 插件 3.5.0-beta05 中修复(参见问题:Ability to selectively suppress warnings during D8 desugaring)。


对于 Android Gradle 插件 3.2.1 - 3.4.1 使用以下解决方法:

来自 Android Gradle 插件 3.2.1 changelog:

Desugaring with D8 is now enabled by default.

所以你应该禁用 D8 的脱糖(在项目的 gradle.properties 文件中):

android.enableD8.desugaring=false

如果你使用R8:

R8 is a new tool for code shrinking and obfuscation that replaces ProGuard. You can start using the preview version of R8 by including the following in your project’s gradle.properties file:

android.enableR8 = true

禁用 R8 脱糖(在项目的 gradle.properties 文件中):

android.enableR8.desugaring=false

我认为这是因为这个class是在Java8中编写的,但是该项目是在Java7.so中编译的我更新如下:

compileOptions {
     sourceCompatibility JavaVersion.VERSION_1_8
     targetCompatibility JavaVersion.VERSION_1_8
 }

这解决了我的问题