How to check if an activity is running in background/foreground from a service?

29,903

Solution 1

Final Update

To check for all activities:

@Override
protected void onStop() {
super.onStop();

    if (AppConstants.isAppSentToBackground(getApplicationContext())) {
        // Do what ever you want after app close simply Close session

    }
}

Method to check our app is running or not:

public static boolean isAppSentToBackground(final Context context) {

    try {
        ActivityManager am = (ActivityManager) context
                .getSystemService(Context.ACTIVITY_SERVICE);
        // The first in the list of RunningTasks is always the foreground
        // task.
        RunningTaskInfo foregroundTaskInfo = am.getRunningTasks(1).get(0);
        String foregroundTaskPackageName = foregroundTaskInfo.topActivity
                .getPackageName();// get the top fore ground activity
        PackageManager pm = context.getPackageManager();
        PackageInfo foregroundAppPackageInfo = pm.getPackageInfo(
                foregroundTaskPackageName, 0);

        String foregroundTaskAppName = foregroundAppPackageInfo.applicationInfo
                .loadLabel(pm).toString();

        // Log.e("", foregroundTaskAppName +"----------"+
        // foregroundTaskPackageName);
        if (!foregroundTaskAppName.equals("Your App name")) {
            return true;
        }
    } catch (Exception e) {
        Log.e("isAppSentToBackground", "" + e);
    }
    return false;
}

Answer updated again

Use the below method with your package name.It will return true if any of your activity is in foreground.

public boolean isForeground(String myPackage){
ActivityManager am = (ActivityManager) getSystemService(ACTIVITY_SERVICE);
 List< ActivityManager.RunningTaskInfo > runningTaskInfo = am.getRunningTasks(1); 

     ComponentName componentInfo = runningTaskInfo.get(0).topActivity;
   if(componentInfo.getPackageName().equals(myPackage)) return true;
return false;
}

Answer Updated

Check this link first Checking if an Android application is running in the background

http://developer.android.com/guide/topics/fundamentals.html#lcycles is a description of the Life Cycle of an android application.

The method onPause() gets called when the activity goes into the background. So you can deactivate the update notifications in this method.

public static boolean isApplicationSentToBackground(final Context context) {
    ActivityManager am = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
    List<RunningTaskInfo> tasks = am.getRunningTasks(1);
    if (!tasks.isEmpty()) {
      ComponentName topActivity = tasks.get(0).topActivity;
      if (!topActivity.getPackageName().equals(context.getPackageName())) {
        return true;
      }
    }

    return false;
  }

add permisions in the menifest as well

<uses-permission android:name="android.permission.GET_TASKS" />

Solution 2

Unfortunately, getRunningTasks() has been deprecated since Android API 21 (Android Lollipop):

This method was deprecated in API level 21. As of LOLLIPOP, this method is no longer available to third party applications: the introduction of document-centric recents means it can leak person information to the caller. For backwards compatibility, it will still return a small subset of its data: at least the caller's own tasks, and possibly some other tasks such as home that are known to not be sensitive.

Share:
29,903
CrazyLearner
Author by

CrazyLearner

Always want to learn new things and don't want to limit my knowledge in any specific sector

Updated on August 09, 2020

Comments

  • CrazyLearner
    CrazyLearner almost 4 years

    I have created a service which starts from an activity's onCreate and stops on the activity's onDestroy method. Now I have to check from a method of the service that whether the activity is running in foreground/background(for some cases like application is forcefully closed). How can I do that?

    1. I need to do this coz as far I know there is no guarantee of calling onDestroy method of an activity if any the application is forcefully closed or any kind of crash. So, my service which starts when my activity launches won't stop after any crash or any forceful closing event.

    2. I have seen this link where foreground activities can be checked. But I need to check a running activity in whatever state (either foreground or background)

  • CrazyLearner
    CrazyLearner over 10 years
    Thanks for your answer, but I dont want to use any method of activity, coz I want to check from a service that whether a specific activity/application is running or not...
  • CrazyLearner
    CrazyLearner over 10 years
    Thanks, your last edit fulfill my task partially, now how can I check from a running service whether all the activities of my application is in background or not....
  • Hassaan Rabbani
    Hassaan Rabbani over 10 years
    @Override protected void onStop() { super.onStop(); if (AppConstants.isAppSentToBackground(getApplicationContext())‌​) { // Do what ever you want after app close simply Close session } }
  • CrazyLearner
    CrazyLearner over 10 years
    To get isApplicationInBackground value, you have made a list of running foreground applications, and check whether my application is over there or not. But there are two cases for an application, not to be in the foreground list: 1. if my application is really in background or 2. my application is crashed and not in background mode. So by those try catch block codes, how can I be sure that my application is not crashed???
  • Hassaan Rabbani
    Hassaan Rabbani over 10 years
    when your application is crashed, it is not in the background list. it is destroyed. being on background means that onPause has been called on the application
  • Hassaan Rabbani
    Hassaan Rabbani over 10 years
    don't forget to up-vote and accept the answer if it helped you. cheers
  • CrazyLearner
    CrazyLearner over 10 years
    yes, I have said it also.(Probably I cant make you understand my comments) My very simple requirement is to make a background application list (not only foreground app list).
  • Hassaan Rabbani
    Hassaan Rabbani over 10 years
  • Zar E Ahmer
    Zar E Ahmer almost 10 years
    if there are three or four apps in background . it will get the latest one because you have set tasks.get(0) and getting am.getRunningTasks(1). what will happen then
  • Abandoned Cart
    Abandoned Cart over 9 years
    Correct me if I am wrong, but the question is about checking an activity from a service within the same application, so wouldn't "at least the caller's own tasks" cover that?
  • Yousha Aleayoub
    Yousha Aleayoub over 9 years
    This method (isApplicationSentToBackground) checks if CURRENT ACTIVITY sent to background, NOT APPLICATION.