Working with Android LifeCycle Observer Architecture Component

What is LifeCycle Observer in Android?

Lifecycle is an Abstract class in Android which attaches with Application lifecycle. It helps to manage the lifecycle event of the activity or fragment.  It helps to manage the state of the application event. We can also define multiple lifecycle events on the same method using annotated. We can manage the lifecycle event like onCreate, onStart and onStop in our custom observer class.

What is the Event in the lifecycle of Android Application?

An event is the lifecycle event that has been triggered by a lifecycle change (such as resuming an activity). In our classes, we can implement callbacks for each of these events so that we can handle lifecycle changes. The arch.lifecycle package provides an Annotation for us to use which means we can annotate the methods within our class which should be triggered upon certain lifecycle events.

Add a dependency in your build.gradle

In this example, we going to implement lifecycle observer in our MainActivity class. To implement Custom Lifecycle observer we are going used getLifecycle() method in onCreate() method which return Lifecycle instance of the activity and we will use an addObserver method where we have passed the object of our custom MainActivityObserver class

To attach event with the method all we have to do just add annotation with the event.

MainActivityObserver implement LifecylceObserver interface. We can also handle multiple lifecycle events within the same annotated method, this allows us to trigger a specific method based on multiple lifecycle events being triggered:

Hope this blog helps you to understand the lifecycle observer feature and write lean code for application lifecycle event.

. . .

Comment

Add Your Comment

Be the first to comment.

css.php
Hire Us!
Brief us about your requirements and we'll get back to you.
Woo! Hooy!
We have just recieved your project brief and our expert will contact you shortly.
Send Again
Close