Detecting when an Android app is in foreground or background

Carlos Daniel
MindOrks
Published in
2 min readMar 5, 2019
Photo by Erik Lundqvist on Unsplash

It’s a rule: every Android app has its own logic, context, and behaviors. And the solutions that may apply successfully to certain cases, may not work to others. One of the particular situations is when we need to identify when our application is on the foreground or background to launch specific tasks. And this is really easy to tackle taking into consideration app’s process lifecycles.

In summary, if we need to detect when our app is coming to the foreground or when it comes to background, leveraging the ProcessLifecycleOwner class and its events are easy to achieve:

Creating the LifeCycleObserver class

It provides lifecycle for the whole application process. It can be used to react to our app coming to the foreground or going to the background with very little code:

The code above creates an observer which will execute some code whenever the app is called either from after clicking the launch icon, another app through intent, or after clicking the app from the app’s stack.

Integrating the Observer within the App

Now, when need to register the LifeCycleObserver class within the app. To achieve this is mandatory to have an Application class in the app (if not, we need to create it) and then in its onCreate() method call the observer class and then registered, as follows:

The above tells the application: every time you come background as there is a class observing this, the app is entering to ON_STOP lifecycle process, then please run the onEnterBackground() method. The same will apply to onEnterForeground() method when the app comes to the foreground, because the app is entering ON_START.

… and that is all folks. Any suggestion doesn’t hesitate to tell it using the comments.

Best!

--

--

Carlos Daniel
MindOrks

Android & Flutter Developer. GDE for Android & Mobile Engineer.