HOW TO CHECK WHETHER AN ANDROID APPLICATION RUNNING IN BACKGROUND

jimmy Smith

Total Post:3

Points:21
Posted by  jimmy Smith
 680  View(s)
Ratings:
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?
  1. Mayank Tripathi

    Post:397

    Points:3117
    Re: How to check whether an android application running in background

    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

NEWSLETTER

Enter your email address here always to be updated. We promise not to spam!