Search code examples
androidproguardandroid-lifecycleandroidxandroid-r8

Android lifecycle observers don't trigger when code is minified by R8


When i build my code with minifyEnabled=true then lifecycle observers don't trigger on any events.

lifecycle.addObserver(object : LifecycleObserver {
    @OnLifecycleEvent(Lifecycle.Event.ON_ANY)
    @Keep
    fun anyEvent(source: LifecycleOwner, event: Lifecycle.Event) {
        // Never triggers
        Timber.i("Source=%s, event=%s", source, event)
    }
})

androidx.lifecycle:lifecycle with version 2.2.0-rc01 (previous versions may be affected too).

The compileSdkVersion is 28 and I'm testing on an Android 10 (API29) emulator.


Solution

  • After about 4 hours I can answer this myself and I hope this keeps someone else from despairing.

    R8 removes some necessary callbacks. I painstakingly went through everything and narrowed it down to these missing:

    20745,20751d20744
    < androidx.lifecycle.ReportFragment$1
    <     public void onActivityPostCreated(android.app.Activity,android.os.Bundle)
    <     public void onActivityPostStarted(android.app.Activity)
    <     public void onActivityPostResumed(android.app.Activity)
    <     public void onActivityPrePaused(android.app.Activity)
    <     public void onActivityPreStopped(android.app.Activity)
    <     public void onActivityPreDestroyed(android.app.Activity)
    27034,27037d27026
    < androidx.lifecycle.ReportFragment$ActivityInitializationListener
    <     public abstract void onCreate()
    <     public abstract void onStart()
    <     public abstract void onResume()
    
    

    The issue is only present if you compile against API 28, but run your code on API 29.

    There is an open issue ticket on this: https://issuetracker.google.com/issues/142778206

    To fix this you can either use compileSdkVersion 29 or include the following proguard rules:

    -keepclassmembers class * extends androidx.lifecycle.EmptyActivityLifecycleCallbacks { *; }
    -keepclassmembers class androidx.lifecycle.ReportFragment$** { *; }