Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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)

like image 492
CrazyLearner Avatar asked Feb 18 '14 10:02

CrazyLearner


People also ask

How do I know if an app is running in the background or foreground?

Whenever a new activity is started and visible to the user its instance is updated in the application class: activeActivity variable, so we can use it to determine which activity is in the foreground from the notifications layer.

How do I check foreground activity?

In your finish() method, you want to use isActivityVisible() to check if the activity is visible or not. There you can also check if the user has selected an option or not.

How does activity come to the foreground?

Activity or dialog appears in foregroundWhen the covered activity returns to the foreground and regains focus, it calls onResume() . If a new activity or dialog appears in the foreground, taking focus and completely covering the activity in progress, the covered activity loses focus and enters the Stopped state.

How do I stop foreground services from activity?

To start a foreground service, call startForeground() . To stop it, call stopForeground() .


1 Answers

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" />
like image 120
Hassaan Rabbani Avatar answered Nov 14 '22 22:11

Hassaan Rabbani