As part of Android Architecture Components Google introduced lifecycle-aware components designed to handle lifecycle events outside of your view layer (Activities and Fragments). All you need to do is create a lifecycle observer for a particular view (lifecycle owner) and subscribe to lifecycle events of your choice. As a result, the code becomes more modular, easier to read and test.

The latest news related to the library came recently from Florina Muntenescu.

A bit of background

There are various reasons why you’d want to detect app open and close events. Perhaps you need to track these events for analytics purposes. Or you may need to message a user on app startup (for instance, communicate updates to privacy policy, announce new content was published, etc.).

Reacting to app foreground events gets more complicated when this message needs to work when deep linking to a specific Activity or coding Instant Apps. It’s all doable but usually requires quite a bit of code involving analyzing Activities in the stack to determine when the app opens or closes.

ProcessLifecycleOwner to the rescue

ProcessLifecycleOwner solves this problem beautifully. It is a special kind of LifecycleOwner that is a composite of all of your Activities. It provides lifecycle for the whole application process. We can use it to react on our app coming to the foreground or going to the background with very little code, as we will see below.

Feel free to skip reading and jump into the source code directly at http://github.com/jshvarts/AppLifecycleDemo.