Detecting when an Android app is in foreground or background

Carlos Daniel
Mar 5, 2019 · 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 method. The same will apply to 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…

Medium is an open platform where 170 million readers come to find insightful and dynamic thinking. Here, expert and undiscovered voices alike dive into the heart of any topic and bring new ideas to the surface. Learn more

Follow the writers, publications, and topics that matter to you, and you’ll see them on your homepage and in your inbox. Explore

If you have a story to tell, knowledge to share, or a perspective to offer — welcome home. It’s easy and free to post your thinking on any topic. Write on Medium

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store