Question

What is lifecycle observer and how to use it correctly?

I have read about new architectural components in Android. So, i wanted to ask what are lifecycle observers and why do we need them? In what cases it is useful? Thanks for your answer!

 46  49448  46
1 Jan 1970

Solution

 50

You can use ProcessLifecycleOwner to get your Application's LifeCycle and to add a class as an observer of these events. You can implement LifecycleObserver in your Application Class:

public class MyApplication extends MultiDexApplication implements LifecycleObserver

@Override
public void onCreate() {
    super.onCreate();

    ProcessLifecycleOwner.get().getLifecycle().addObserver(this);

}

// Add these Lifecycle methods to observe when your app goes into the background or to the foreground:

@OnLifecycleEvent(Lifecycle.Event.ON_RESUME)
public void appInResumeState() {
    Toast.makeText(this,"In Foreground",Toast.LENGTH_LONG).show();
}

@OnLifecycleEvent(Lifecycle.Event.ON_PAUSE)
public void appInPauseState() {
    Toast.makeText(this,"In Background",Toast.LENGTH_LONG).show();
}

// Add the following in your build.gradle file

implementation 'android.arch.lifecycle:extensions:1.1.1'

//Also In Activities or Fragments

You can also use them to reduce the complexity of code by creating different components which are implementing LifecycleObserver and then pass the lifecycle of activity to these components. This way you can split up the huge complexity to different components.

class MainActivity : AppCompatActivity(), LifecycleObserver {

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
        ReduceComplexComponent().registerLifecycle(lifecycle)

    }

}

class ReduceComplexComponent : LifecycleObserver{

    registerLifecycle(lifecycle : Lifecycle){
       lifecycle.addObserver(this)
    }

    @OnLifecycleEvent(Lifecycle.Event.ON_RESUME)
    fun resume() {
       Log.d("OnResume","ON_RESUME")
    }

    @OnLifecycleEvent(Lifecycle.Event.ON_PAUSE)
    fun pause() {
       Log.d("onPause","ON_PAUSE")
    }
}

This way you can listen to activity or fragment lifecycle events in separate components.

We can also manually fetch the current state of our lifecycle instance in Activity and that we can do by using its getCurrentState()

A State also has an isAtLeast() method that we can use to perform comparisons against the current lifecycle state

2018-12-07

Solution

 22

@OnLifecycleEvent is deprecated so many of the answers that used to be helpful here are no longer helpful. If you're not currently using Java 8 yet, you'll need to update your build.gradle first. We can now utilize DefaultLifecycleObserver or LifecycleEventObserver. See examples below.

To start, you can use ProcessLifecycleOwner to get your Application's lifecycle:

ProcessLifecycleOwner.get().getLifecycle()

DefaultLifecycleObserver:

lifecycle.addObserver(object: DefaultLifecycleObserver {
    override fun onResume(owner: LifecycleOwner) {
        super.onResume(owner)
        TODO()
    }
    override fun onPause(owner: LifecycleOwner) {
        TODO()
        super.onPause(owner)
    }
})

LifecycleEventObserver:

lifecycle.addObserver(object: LifecycleEventObserver {
    override fun onStateChanged(source: LifecycleOwner, event: Lifecycle.Event) {
        when (event) {
            Lifecycle.Event.ON_RESUME -> TODO()
            Lifecycle.Event.ON_PAUSE -> TODO()
            else -> { }
        }
    }
})

How to update to Java 8 and explanation of why OnLifecycleEvent is deprecated: https://stackoverflow.com/a/70384221/3422470

2022-01-21