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!

- 527
- 6
- 19

- 1,802
- 2
- 16
- 35
-
3Very detailed explanation here: https://developer.android.com/topic/libraries/architecture/lifecycle – denvercoder9 Sep 17 '18 at 14:05
6 Answers
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

- 274
- 2
- 10

- 1,806
- 22
- 21
-
2If anyone looking for Kotlin solution to observe Application lifecycle Events, can check this link. https://handyopinion.com/easiest-way-to-observe-application-lifecycle-events-in-kotlin-android/ – Asad Ali Choudhry Nov 24 '19 at 08:12
-
2Will the method registered with event Lifecycle.Event.ON_STOP gets called when the application is destroyed ? In my application class using lifecycleobserver, detecting app foreground and app background using ON_START and ON_STOP events. I have a doubt that ON_STOP event is not getting triggered when the app is being destroyed. Detecting app foreground and background logic is working fine. Do i need to register ON_DESTROY event to get callback when app is being destroyed ? – K Pradeep Kumar Reddy Oct 24 '20 at 07:12
-
2Don't you have to call `ProcessLifecycleOwner.get().getLifecycle().addObserver(this);` on the main thread these days? – portfoliobuilder May 26 '21 at 03:56
-
7`@OnLifecycleEvent` is deprecated. https://developer.android.com/jetpack/androidx/releases/lifecycle#2.4.0-beta01 – Akito Nov 19 '21 at 15:09
-
1
-
I added a new answer to replace the deprecated `OnLifecycleEvent`: https://stackoverflow.com/a/70808707/3422470 – James Jan 21 '22 at 23:33
@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

- 4,573
- 29
- 32
May be a little late to the party, but another nice use-case of lifecycles (except for the obvious ViewModel stuff), is to let many components of the app un-register themselves when the relevant activity is getting destroyed, or simply out of screen.
For example, I have a static factory that creates dialogs, and using lifecycle I can dismiss the dialogs without cluttering the host activity with the old stuff like Dialog mDialog = ...
and void onPause(){ ... if (mDialog !null && mDialog.isShowing()) mDialog.cancel() }
Some code:
DialogUtils.java:
public static void showConfirmDialog(Lifecycle lifecycle, String title, String msg, Runnable okRunnable) {
AlertDialog dialog = AlertDialog.Builder(mAppContext)
/* configuration stuff ... */
.build();
dialog.show();
lifecycle.addObserver(new LifecycleObserver() {
@OnLifecycleEvent(Lifecycle.Event.ON_PAUSE)
public void cancelDialog() {
if (dialog.isShowing()) { // if not already dismissed by main-button tap
dialog.cancel();
}
}
});
}
MyActivity.java:
public class MyActivity extends AppCompatActivity {
/* stuff... onCreate()... other stuff... */
private void confirmDeleteUser(User user){
DialogUtils.showConfirmDialog(
MyActivity.this.getLifecycle(), // all activities & fragment have lifecycles
"Confirm Delete",
"Action cannot be undone. Sure to continue?",
new Runnable() { /* stuff... */ }
);
// Voilà!
// activity no needs to store reference to the dialog and cancel manually on pause
// it's a fire-and-forget action
}
}

- 1,869
- 1
- 22
- 28
-
2I don't understand your answer. AlertDialogs are destroyed by the system on configuration changes.Why should you cancel them manually? – The incredible Jan Jan 22 '20 at 14:29
-
2bcs even though they are being destroyed, your activity receives an exception before getting to onDestory(...) so you might not get your implementation running – Re'em Jan 22 '20 at 16:50
-
1I don't know what "bcs" means but I never got any exception in my activity and I don't know why I should. I use it like this: https://stackoverflow.com/a/2115770/2523899 – The incredible Jan Jan 23 '20 at 08:59
-
`@OnLifecycleEvent` is deprecated. I added a new answer to replace the deprecated `@OnLifecycleEvent`: stackoverflow.com/a/70808707/3422470 – James Mar 08 '22 at 22:00
LifeCycleObserver
is part of Google released Android Jetpack LifeCycle Architecture components, and it is an interface that allows you to observe a LifeCycle-aware observable component, typically a LifeCycleOwner
(Activity/Fragment), in order to interact with the LifeCycle events and states associated to this component; so you can monitor foreground and background lifeCycle events.
Here are some useful links with typical usage
- https://developer.android.com/reference/androidx/lifecycle/Lifecycle
- https://medium.com/@MinaSamy/android-architecture-components-lifecycle-433ace1ec05d
- https://riggaroo.co.za/android-architecture-components-looking-lifecycles-part-3/
- https://proandroiddev.com/make-your-custom-view-lifecycle-aware-its-a-piece-of-cake-90b7c0498686

- 37,492
- 7
- 60
- 84
-
2
-
Please update Lifecycle link to https://developer.android.com/reference/androidx/lifecycle/Lifecycle – Mussa Mar 15 '22 at 00:28
lifecycle-extensions
API have been deprecated.
lifecycle-extensions Artifact Deprecation: With the above deprecation of
ViewModelProviders.of()
, this release marks the deprecation of the last API inlifecycle-extensions
and this artifact should now be considered deprecated in its entirety. We strongly recommend depending on the specific Lifecycle artifacts you need (such aslifecycle-service
if you’re usingLifecycleService
andlifecycle-process
if you’re usingProcessLifecycleOwner
) rather thanlifecycle-extensions
as there will not be a future2.3.0
release oflifecycle-extensions
.
If you want to continue to use ProcessLifecycleOwner
,
it is recommended to add this dependency:
implementation "androidx.lifecycle:lifecycle-process:2.2.0"
Ref:
https://developer.android.com/jetpack/androidx/releases/lifecycle#version_220_3
https://androidx.tech/artifacts/lifecycle/lifecycle-extensions/
https://developer.android.com/reference/androidx/lifecycle/ProcessLifecycleOwner

- 41
- 1
You use them in order to reduce the callbacks and clean-ups of components due to Lifecycle events
of your app. For instance you have a Handler/Runnable
that is running from a Thread
somewhere and you need to have some callbacks/interfaces in order to stop and remove the listener
when onStop()
is called; thus using the new "Jetpack LifeCycle Architecture components" you can make your component/class "lifecycle-aware" hence controlling it easily from the Activity/Fragment using it!
More info as stated above: https://developer.android.com/topic/libraries/architecture/lifecycle

- 5,052
- 5
- 34
- 43