Background and Foreground events with Android Architecture Components

Lately on 47 Degrees, I had the need to detect when an Android application goes to background or foreground to start or stop some services.

The usual way to do this is with an activity counter, incrementing or decrementing when an Activity starts or stops and reacting when the counter reaches some values.

Fortunately, you can use Android Architecture Components to get same behavior using only a few lines.

I am going to show you how to use Architecture Components to detect background and foreground events but I am not going to explain detailedly how it works, you can check the documentation if you need more information.

Show me the code

If you are still not using Architecture Components then you have to add the dependencies to your build.gradle file before using it:

kapt "android.arch.lifecycle:compiler:1.1.1"
implementation "android.arch.lifecycle:extensions:1.1.1"

Now it’s time to create your lifecycle aware component. You just need to implement the LifecycleObserver interface and add annotations to those methods where you want to monitor the lifecycle statuses. Example:

class ApplicationObserver : LifecycleObserver {

fun onForeground() {
// App goes to foreground

fun onBackground() {
// App goes to background

You need to subscribe this observer to a Lifecycle from a LifecycleOwner in order to start to receive lifecycle events. There are several available lifecycle owners ready to use for Activity, Fragment, etc. but, in this case, you only interested in one called ProcessLifecycleOwner.

The easiest way to add your ApplicationObserver to ProcessLifecycleOwner is using your custom Android Application class:

class MyApplication : Application() {

override fun onCreate() {

That’s all. You don’t need count activities anymore, just a couple of lines! 🎉

Spoiler: ProcessLifecycleOwner counts activities internally

If you want to dig deeper, you can check ProcessLifecycleOwner documentation to know more details about when the events are being triggered by this lifecycle

This paragraph from the docs is specially important:

You can consider this LifecycleOwner as the composite of all of your Activities, except that ON_CREATE will be dispatched once and ON_DESTROY will never be dispatched. Other lifecycle events will be dispatched with following rules: ProcessLifecycleOwner will dispatch ON_START, ON_RESUME events, as a first activity moves through these events. ON_PAUSE, ON_STOP, events will be dispatched with a delay after a last activity passed through them.

Thanks for reading this article. If you liked or found helpful this article remember to click ❤ below to recommend it. It helps me a lot.

Also, you can follow me on Twitter, Github, Facebook or Linkedin.