Android #1 How to Check if the App is in Background or Foreground

Image for post
Image for post
“A smartphone on a wooden surface next to a cup of coffee” by Kim S. Ly on Unsplash

Sharing will enrich everyone with more knowledge

Coming across the above quote made me start writing about the things I know, I learn everyday.

Today we will look into the important requirement for Android app developers i.e. checking the android app state, whether in foreground or background.

There is an old way to achieve this, that is by Iterating through current running processes using ActivityManager.RunningAppProcessInfo. However, this approach is not memory efficient and permission used for this purpose GET_TASKS is already deprecated.

Thanks to the I/O and android architecture components. Now we have a Better way to do this by using class ProcessLifecycleOwner and LifecycleObserver.

As per the Android docs : ProcessLifecycleOwner provides lifecycle for the whole application process. LifecycleObserver does not have any methods, instead, relies on onLifecycleEvent annotated methods.This provides an Annotation for us to use which means we can annotate the methods within our class which can be called upon certain lifecycle events. You can use something like this :

@OnLifecycleEvent(Lifecycle.Event.ON_START)
public void onMoveToForeground() {
// app moved to foreground
}

Above method is called every time your app moves into foreground. Similarly to check when app moves into background we can use

@OnLifecycleEvent(Lifecycle.Event.ON_STOP)
public void onMoveToBackground() {
// app moved to background
}

Lots of talking. Let’s make it happen!!!!

Add the following dependencies to your build.gradle file:

implementation "android.arch.lifecycle:extensions:1.1.1"
annotationProcessor "android.arch.lifecycle:compiler:1.1.1"
// alternately-if using Java8, use following instead of compiler
implementation "android.arch.lifecycle:common-java8:1.1.1"

You can make your application class implement LifecycleObserver and make use of annotated methods.

https://gist.github.com/NeerajMoudgil/cdea451f7bc79d33d1a1513eb1e2031d

Make sure in your AndroidManifest.xml you don’t miss adding your custom application class like this:

<application
android:name="
MyApplication"

Now you can make use of

MyApplication.wasInBackground

to check app is in foreground or background.

Cheer me with claps if the post is helpful.

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