Search code examples
android-gradle-pluginandroid-lifecycle

Compiler error only in Android Studio but not in Gradle build: abstract base class member getLifecycle() not implemented


In my Android project in AndroidStudio a class (named MyService below), which extends LifecycleService, is marked with the following error message:

Class 'MyService' is not abstract and does not implement abstract base class member public abstract fun getLifecycle(): Lifecycle defined in androidx.lifecycle.LifecycleService

But the build with Gradle is fine, and when I navigate to the class LifecycleService, it is neither abstract nor is the getLifecycle method missing, due to the following definition:

override val lifecycle: Lifecycle
    get() = dispatcher.lifecycle

which should fulfill the interface method getLifecycle of LifeCycleOwner.

So it seems, that AndroidStudio is using other libraries than Gradle. But when I navigate in AndroidStudio it seems, that the gradle libraries are used. Any explanation, what is going on here, and how I can fix it?


Solution

  • The problem in transitive library dependencies

    Explanation

    AppCompat, Activity, Fragment and other AndroidX libraries have outdated versions of lifecycle-common library in their dependencies. Apparently you are using a new version of the lifecycle dependency in one of the modules, but in other modules you are not using it at all and the older version is automatically selected. The new version of lifecycle has changed the description of the androidx.lifecycle.LifecycleOwner interface and therefore Android Studio considers them different

    Lifecycle version 2.6.1

    public interface LifecycleOwner {
    
        public val lifecycle: Lifecycle
    }
    

    Lifecycle version 2.5.1

    public interface LifecycleOwner {
    
        @NonNull
        Lifecycle getLifecycle();
    }
    

    Solution 1:

    You need to explicitly specify the new version of the lifecycle-common dependency in the other modules (not necessarily in all, but only in those where lifecycle is used transitively)

    implementation 'androidx.lifecycle:lifecycle-common:2.6.1'
    

    Solution 2:

    You can roll back versions of lifecycle libraries to 2.5.1, which is used in the latest version of the library currently "androidx.appcompat:appcompat:1.6.1

    implementation 'androidx.lifecycle:lifecycle-common:2.5.1'