How to check whether an android application running in background

 How to detect weather an android application is running in background or not ,by background, I mean none of the application's activities are currently visible to the user?
Last updated:10/12/2015 7:07:01 AM

1 Answers

Mayank Tripathi
Mayank Tripathi

Track visibility of your application by yourself using Activity.onPause, Activity.onResume methods. Store "visibility" status in some other class. Good choices are your own implementation of the Application or a Service

Example
Implement custom Application class (note the isActivityVisible() static method):

public class MyApplication extends Application {
  public static boolean isActivityVisible() {
    return activityVisible;
  }  
  public static void activityResumed() {
    activityVisible = true;
  }
  public static void activityPaused() {
    activityVisible = false;
  }
  private static boolean activityVisible;
}
Register your application class in AndroidManifest.xml:
<application
    android:name="your.app.package.MyApplication"
    android:icon="@drawable/icon"
    android:label="@string/app_name" >
Add onPause and onResume to every Activity in the project (you may create a common ancestor for your Activities if you'd like to, but if your activity is already extended from MapActivity/ListActivity etc. you still need to write the following by hand):

@Override
protected void onResume() {
  super.onResume();
  MyApplication.activityResumed();
}
@Override
protected void onPause() {
  super.onPause();
  MyApplication.activityPaused();
}
 
Also,
ActivityLifecycleCallbacks were added in API level 14 (Android 4.0). You can use them to track whether an activity of your application is currently visible to the user. Check Cornstalks' answer below for the details.

Answer