Detect android app is in foreground or background

In This Tutorial

This question comes a lot when you need to detect an Android app goes to the background and come back to the foreground (android app is in foreground or background state). Activities and Fragments have all the callbacks to detect life-cycle change, but there is nothing for the whole application. We are able to detect when an app exist using on onBackPress() method but not able to detect when a home button is pressed or app just goes to back stack.

So how do you detect when a user backgrounds and foregrounds your app. This is an example of how your could detect Application life-cycle events (android app is in foreground or background state).

detect app is in foreground or background

How we detect android app is in foreground or background

Detect forgeround state

To detect a foreground state we are using here an onStart() method of our activity lifecycle.

Detect background state

It may be late but there’s a reliable method in Ice Cream Sandwich (API 14) and Above.

Turns out that when your app has no more visible UI, a callback is triggered. The callback, which you can implement in a custom class, is called ComponentCallbacks2. This callback is only available in API Level 14 (Ice Cream Sandwich) and above.

Your activity is an indirect sub class of ComponentCallbacks2 interface. So to use onTrimMemory method you need only to override it in you activity or base activity.

Code

Inside onTrimMemory method we are comparing level with ComponentCallbacks2.TRIM_MEMORY_UI_HIDDEN to detect app is in background.

MainActivity.java

To learn how to implement OnItemClickListener on RecyclerView click here

About Jitendra Singh

Hi there, I'm a founder at androidfizz and a career oriented entity in an area of development of android based mobile applications.

View all posts by Jitendra Singh →

One Comment on “Detect android app is in foreground or background”

  1. Hi, if I want start activity when app is in background, the activity it is not started

    @Override
    public void onTrimMemory(int level) {
    super.onTrimMemory(level);
    if (level == ComponentCallbacks2.TRIM_MEMORY_UI_HIDDEN) {
    Intent intent = new Intent(this, Login2.class);
    startActivity(intent);
    Toast.makeText(this, “App In Background”, Toast.LENGTH_SHORT).show();
    }
    }

Leave a Reply

Your email address will not be published. Required fields are marked *