Foreground or Background ?

Know how to detect your application’s visibility, in Android

Rajeev Ranganathan
3 min readJun 14, 2020

--

Knowing your app’s visibility is crucial in some of the use-cases when you might have to perform some actions like, release/acquire 3rd party SDK resources when your app moves between foreground & background.

In Android, to know an Activity/Fragment lifecycle , there are lifecycle callbacks. But , do we have callbacks to know if an app is currently in foreground/background ?

Well, the answer is , NO & .. YES

confused? Let me explain,

No , there’s no direct way of achieving this.We don’t get a callback like we do in case of activity or a fragment.

Yes, we can still achieve this.Using the following ways.

1.Single Activity architecture

If you are unaware/ still thinking to use this architecture, here’s a nice article that explains.

Already following it ? then congrats!!.

In Single Activity architecture, your app contains only one Activity. Hence, to know your app’s visibility, implement it’s onStart and onStop methods. These two methods are executed only when your app moves between foreground & background.

Let’s look at our next alternative.

2.Using ActivityLifeCycleCallback

  1. Create an interface AppLifeCycleListener , which is a contract on what you need to do when the app is foreground/background

2. Implement it

3. Implement ActivityLifecycleCallback in your custom application class. Keep track of the number of activities in its onActivityStarted and onActivityStopped methods.Register it in onCreate

Here’s how it works in case of

a) Foreground:

b) Background

when the user presses Home / back

& it work’s like a charm

But wait, that’s all? Don’t you think you can do better?

Of Course..

3.LifecycleObserver

LifecycleObserver , doesn’t have any methods but it relies on annotated methods.It is a part of Android architecture components , which in turn is now part of Jetpack. To achieve our objective

  1. Include the lifecycle-runtime and lifecycle-process as the dependency

2.Implement LifeCycleObserver in AppProcessLifecycleListener. Add two methods, onAppBackground and onAppForeground and annotate it with @OnLifecycleEvent(Lifecycle.Event.ON_STOP) & @OnLifecycleEvent(Lifecycle.Event.ON_START)

That means , the above two methods are called during the events “ON_STOP” and “ON_START”. You can read more about it here

3. Now the last step is to register the above listener in your custom application class, as an observer to the lifecycle of your app

Here’s how it works compared to the previous approach

That’s it. easy-peasy! Now you can celebrate!!

If this article was of any help to you , please don’t forget to click on 👏 and recommend it to others.

Happy coding!

--

--

Rajeev Ranganathan

Programmer (Android / iOS)|❤️ Ux/UI design| Krav maga/MMA/Boxing practitioner | Kotlin over Java |Tea over coffee | Monaco over Menlo