6

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)

Community
  • 1
  • 1
CrazyLearner
  • 782
  • 3
  • 11
  • 28

4 Answers4

12

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" />
Community
  • 1
  • 1
Hassaan Rabbani
  • 2,469
  • 5
  • 30
  • 55
  • 1
    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 Feb 18 '14 at 10:26
  • 1
    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.... – CrazyLearner Feb 18 '14 at 10:34
  • @Override protected void onStop() { super.onStop(); if (AppConstants.isAppSentToBackground(getApplicationContext())) { // Do what ever you want after app close simply Close session } } – Hassaan Rabbani Feb 18 '14 at 10:37
  • 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??? – CrazyLearner Feb 18 '14 at 10:52
  • 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 Feb 18 '14 at 10:56
  • 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). – CrazyLearner Feb 18 '14 at 11:07
  • let us [continue this discussion in chat](http://chat.stackoverflow.com/rooms/47742/discussion-between-hassaan-rabbani-and-crazylearner) – Hassaan Rabbani Feb 18 '14 at 11:18
  • 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 – Zar E Ahmer Jul 02 '14 at 09:47
  • This method (isApplicationSentToBackground) checks if CURRENT ACTIVITY sent to background, NOT APPLICATION. – Yousha Aleayoub Mar 11 '15 at 09:41
7

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.

Sufian
  • 6,405
  • 16
  • 66
  • 120
Sam Lu
  • 3,448
  • 1
  • 27
  • 39
  • 2
    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? – Abandoned Cart Dec 19 '14 at 01:22
0

Try this method to check your app is in background or not:

public boolean isAppIsInBackground(Context context) {
        boolean isInBackground = true;
        ActivityManager am = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
        if (Build.VERSION.SDK_INT > Build.VERSION_CODES.KITKAT_WATCH) {
            List<ActivityManager.RunningAppProcessInfo> runningProcesses = am.getRunningAppProcesses();
            for (ActivityManager.RunningAppProcessInfo processInfo : runningProcesses) {
                if (processInfo.importance == ActivityManager.RunningAppProcessInfo.IMPORTANCE_FOREGROUND) {
                    for (String activeProcess : processInfo.pkgList) {
                        if (activeProcess.equals(context.getPackageName())) {
                            isInBackground = false;
                        }
                    }
                }
            }
        } else {
            List<ActivityManager.RunningTaskInfo> taskInfo = am.getRunningTasks(1);
            ComponentName componentInfo = taskInfo.get(0).topActivity;
            if (componentInfo.getPackageName().equals(context.getPackageName())) {
                isInBackground = false;
            }
        }

        return isInBackground;
    }
Yessine Mahdouani
  • 1,225
  • 12
  • 24
-3

check this link & especially check the Answer Which shows this part of code

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;
}

Hope this help you.

Community
  • 1
  • 1
i.n.e.f
  • 1,773
  • 13
  • 22