androidgradleandroid-r8

R8 removes entire classes it shouldn't


After migrating Gradle from 8.4 to 8.9 and Gradle plugin from 8.3.2 to 8.7.0, R8 is failing when building a signed release APK.

Missing class com.my.package.MyClass$Companion (referenced from: void common.my.package.workers.SyncWorker.<init>(android.content.Context, androidx.work.WorkerParameters, com.my.package.Dao))

It fails with many more missing classes. I did add -keep class com.my.package.** { *; } to the app module (in proguard-rules.txt) and to my other modules (in consumer-rules.txt) but to no avails. I also added android.enableR8.fullMode=false to my gradle.properties but it didn't change anything. Android Studio do generates missing-rules.txt with a bunch of -dontwarn which make the build pass but the app crashes right away with the same missing classes error.

Any Idea of how I can fix this? I see the documentation saying


Solution

  • I was able to resolve the issue in my case, and you might have the same issue. You indirectly mentioned that you have multiple modules. Do you by any chance set the minify flag to true for them, for the library modules?

    This was the case with me, and that was the problem. I was able to better isolate the issue, it wasn't about upgrading the Gradle version to "8.9", rather, it was about upgrading the AGP to "8.4.0" and higher (which can also be valid for you since you had started with "8.3.2").

    The problem is explained here: https://developer.android.com/build/releases/past-releases/agp-8-4-0-release-notes#library-classes-shrunk

    Based on how I understand it with my limited understanding of it, it seems like starting with that version of AGP, when the minify is set to true, it will try to minify the lib module much sooner in the process, as opposed to doing it at the very end. In a way, the app module will have to use a minified version of the lib modules.

    Setting "isMinifyEnabled" to false for my library modules, and keeping it to true for my app module did resolve the issue for me. There was even no need to disable full mode for R8.

    I think that setting the flags like this is safe, as it is explained for example here (the whole problem is also explained here): https://www.reddit.com/r/androiddev/comments/1e8ke67/agp_84_and_hilt_android_library_modules_in/

    or here:

    https://www.reddit.com/r/androiddev/comments/xubcff/when_using_proguard_do_i_have_to_set/

    Sorry in advance, if this is not the case with you.