Home > DeveloperSection > Forums > How to check whether an android application running in background
jimmy Smith
jimmy Smith

Total Post:3

Points:21
Posted on    October-12-2015 6:37 AM

 Android Android  Android Libraries 
Ratings:


 1 Reply(s)
 441  View(s)
Rate this:
 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?


Mayank Tripathi
Mayank Tripathi

Total Post:397

Points:3117
Posted on    October-12-2015 7:07 AM

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.

Don't want to miss updates? Please click the below button!

Follow MindStick