42

After updating lifecycle library to 2.4.0 Android studio marked all Lifecycle events as deprecated.

@OnLifecycleEvent(Lifecycle.Event.ON_CREATE)
fun create() {
    tts = TextToSpeech(context, this)
}

@OnLifecycleEvent(Lifecycle.Event.ON_PAUSE)
fun stopTTS() {
    tts?.stop()
}

Is there any equivalent replacement such as DefaultLifecycleObserver ?

Thomas S.
  • 5,804
  • 5
  • 37
  • 72
Vahe Gharibyan
  • 5,277
  • 4
  • 36
  • 47

6 Answers6

39

It's deprecated because they now expect you to use Java 8 and implement the interface DefaultLifecycleObserver. Since Java 8 allows interfaces to have default implementations, they defined DefaultLifecycleObserver with empty implementations of all the methods so you only need to override the ones you use.

The old way of marking functions with @OnLifecycleEvent was a crutch for pre-Java 8 projects. This was the only way to allow a class to selectively choose which lifecycle events it cared about. The alternative would have been to force those classes to override all the lifecycle interface methods, even if leaving them empty.*

In your case, change your class to implement DefaultLifecycleObserver and change your functions to override the applicable functions of DefaultLifecycleObserver. If your project isn't using Java 8 yet, you need to update your Gradle build files. Put these in the android block in your module's build.gradle:

    compileOptions {
        sourceCompatibility JavaVersion.VERSION_1_8
        targetCompatibility JavaVersion.VERSION_1_8
    }
    kotlinOptions {
        jvmTarget = '1.8'
    }

*Note: Well, they could have used the old Java pattern of providing an interface Adapter class that has open, empty implementations of each interface function. The downside with this approach, though, is that the listener must be solely a listener. But I think that should usually be the case anyway if you care about encapsulation.

Tenfour04
  • 83,111
  • 11
  • 94
  • 154
39

Your class must implement DefaultLifecycleObserver like so

public class MyFavoriteClass implements DefaultLifecycleObserver

Then implement the methods needed (Android Studio: ALT + i)

@Override
public void onResume(@NonNull LifecycleOwner owner) {
    methodRunsAtOnResume();
}

@Override
public void onDestroy(@NonNull LifecycleOwner owner) {
    myFavoriteOnDestroyMethod();
}

In your activity or fragment add this to onCreate()

@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    MyOtherClass clazz = new MyOtherClass();
    getLifecycle().addObserver(clazz);
}

To implement it more correctly create your own observer class, pass the object you like to observe to it. Nice article about it is https://medium.com/@MinaSamy/android-architecture-components-lifecycle-433ace1ec05d

Troy
  • 690
  • 1
  • 7
  • 25
S. Gissel
  • 1,788
  • 2
  • 15
  • 32
  • 1
    This is the correct answer to the main question according to the documentation here: https://developer.android.com/topic/libraries/architecture/lifecycle#lco - not the one marked as a correct in this thread. – Piotr Wittchen Mar 20 '22 at 18:43
  • @PiotrWittchen, my answer is short on detail, but the first sentence of the third paragraph is describing what is explained in detail here. – Tenfour04 Jul 26 '22 at 16:27
7

You can simply replace the deprecated @OnLifecycleEvent with DefaultLifecycleObserver as you can see in the following example:

Old code:

@OnLifecycleEvent(Lifecycle.Event.ON_CREATE)
fun onCreate() {
    // your code
}

New code:

override fun onCreate(owner: LifecycleOwner) {
    super.onCreate(owner)
    // your code
}
Agna JirKon Rx
  • 2,321
  • 2
  • 29
  • 44
6

In order to keep track of the current Activity's lifecycle, you can use the LifecycleEventObserver class. First, create a callback,

private val lifecycleEventObserver = LifecycleEventObserver { source, event ->
    if (event == Lifecycle.Event.ON_RESUME ) {
        Log.e( "APP" , "resumed" )
    }
    else if ( event == Lifecycle.Event.ON_PAUSE ) {
        Log.e( "APP" , "paused" )
    }
}

Attach the callback in the onCreate method of the Activity using lifecycle.add( Observer ) method,

lifecycle.addObserver( lifecycleEventObserver )
Shubham Panchal
  • 4,061
  • 2
  • 11
  • 36
3

Firstly, Inherit the class from LifecycleEventObserver

Then in the init block or onCreate add this line:

lifecycle.addObserver(this)

or if you are working in non-activity/fragment class then add this instead:

ProcessLifecycleOwner.get().lifecycle.addObserver(this)

Then override onStateChanged function:

override fun onStateChanged(source: LifecycleOwner, event: Lifecycle.Event) {
    when(event){
        Lifecycle.Event.ON_STOP -> TODO()
        Lifecycle.Event.ON_CREATE -> TODO()
        Lifecycle.Event.ON_START -> TODO()
        Lifecycle.Event.ON_RESUME -> TODO()
        Lifecycle.Event.ON_PAUSE -> TODO()
        Lifecycle.Event.ON_DESTROY -> TODO()
        Lifecycle.Event.ON_ANY -> TODO()
    }
}

Also, if you have implemented androidx-startup in manifest then change that code to this otherwise LifecycleEventObserver won't call:

<provider
         android:name="androidx.startup.InitializationProvider"
         android:authorities="${applicationId}.androidx-startup"
         android:exported="false"
         tools:node="merge">

<!-- If you are using androidx.startup to initialize other components then define it in this block-->
         
</provider>

Ali Azaz Alam
  • 1,782
  • 1
  • 16
  • 27
2

You can create this function to use DefaultLifecycleObserver and call it in onCreate() lifecycle callback of an Activity

    private fun addDefaultLifeCycleObserver() {
        val defaultLifecycleObserver = object : DefaultLifecycleObserver {
            override fun onCreate(owner: LifecycleOwner) {
                super.onCreate(owner)
                Log.d("Main", "DefaultLifecycleObserver - onCreate")
            }
        }
        lifecycle.addObserver(defaultLifecycleObserver)
    }
Vahe Gharibyan
  • 5,277
  • 4
  • 36
  • 47
Raj Kanchan
  • 450
  • 6
  • 11