Detecting when an Android app is in foreground or background

Carlos Daniel
Mar 5 · 2 min read
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!

MindOrks

Our community publishes stories worth reading on Android Development

Carlos Daniel

Written by

GDE for Android & Android Developer @Webcat LLC

MindOrks

MindOrks

Our community publishes stories worth reading on Android Development

Welcome to a place where words matter. On Medium, smart voices and original ideas take center stage - with no ads in sight. Watch
Follow all the topics you care about, and we’ll deliver the best stories for you to your homepage and inbox. Explore
Get unlimited access to the best stories on Medium — and support writers while you’re at it. Just $5/month. Upgrade