2

I'm trying to determine when my app is being resumed after the user closed it, in any way, pressing home button, back button or switching to another app.

What I need to do is to set a boolean when the app goes in background, so, when it is resumed, I know that it was in background before and I can act accordingly.

I tried to use onResume and onPause methods in activities to know when the app goes in background and it is then resumed, but as only one activity can be alive at at time, I had no success. When an activity is paused, this doesn't mean that the app went to background, because another activity could have been launched, but the onResume event of that activity will trigger only after the previous one has paused.

I've also tried to list all the apps in foreground, but with no success, if I put my app in background resuming another app, my app always results to be in the foreground.

I read that since Android 4 there is a new method to know when the app is in foreground, but I need my app to be compatible with Android 3.0 devices too.

Here is the code I tried putting in every single activity (MyApp is my Application name):

@Override
protected void onResume() {
    super.onResume();
    MyApp.isPaused = false;
}

@Override
protected void onPause() {
    super.onPause();
    MyApp.isPaused = true;
}

This is also my attempt to list all the apps in foreground:

ActivityManager activityManager = (ActivityManager)((Activity) currentContext).getSystemService( ACTIVITY_SERVICE );
  List<RunningAppProcessInfo> appProcesses = activityManager.getRunningAppProcesses();
  for(RunningAppProcessInfo appProcess : appProcesses){
      if(appProcess.importance == RunningAppProcessInfo.IMPORTANCE_FOREGROUND){
          if(appProcess.processName.equals("com.xxx.myapp")) {
               Log.i("MyApp", "it's in foreground");
          }
          Log.i("MyApp", appProcess.processName);
      }
  }
dany84
  • 251
  • 1
  • 6
  • 17

6 Answers6

2

You are absolutely correct :) Because only one activity can be alive at a time so you need something which remains alive through out the application life cycle :) like Application instance itself or you can also make use of shared preference for that matter. But seriously using shared prefference for checking lifecycle is wrong choice if you ask me.

If I was in your position I would have gone for Application class :) Here is code if you want to do the same :)

import android.app.Application;

/**
 * Created by sandeepbhandari on 3/3/16.
 */
public class AppService extends Application{
    private static AppService sInstance;
    public static boolean isGoingToBackGround=false;

    @Override
    public void onCreate() {
        super.onCreate();
        sInstance = this;
    }

    public static AppService getInstance() {
        return sInstance;
    }
}

In all your activities onPause just set

AppService service = AppService.getInstance();
        service.isGoingToBackGround =true;

And in onResume check the same variablethats all :) and yeah if you want to use your application class rather than default Application you have to make change to manifest.xml

<application
        android:name=".AppService"

Thats all :)

Sandeep Bhandari
  • 19,999
  • 5
  • 45
  • 78
  • getInstance() returns null only if you dont secify this class as you application class in AndroidManifest.xml sir :) It is a working code :) – Sandeep Bhandari Mar 04 '16 at 08:58
  • thank you, but if when an activity is paused it doesn't mean that the app is in background. It could have paused because another activity is being launched and not because the app has been closed. – dany84 Mar 04 '16 at 09:18
  • Then try onStop :) onStop gets called when application is completely hidden and onPause gets called when activity is partially hidden as per docs :) http://developer.android.com/training/basics/activity-lifecycle/pausing.html you can also try onWindowFocusChanged on activity :) – Sandeep Bhandari Mar 04 '16 at 09:21
  • Here is a blog to determine foreground and background status of app as a whole http://vardhan-justlikethat.blogspot.in/2013/05/android-solution-to-detect-when-android.html check this out :) – Sandeep Bhandari Mar 04 '16 at 09:32
  • It doesn't work, onStop is called even when the app is still running. I'll check the other link you posted, thanks – dany84 Mar 04 '16 at 09:37
2

This class provides a singleton to determine "the activity in background" status. It uses a timer with a threshold(i.e. 0.3s) to determine the activity is went to background or not.

One thing has to point out is that if the user resumes to the activity within the threshold (i.e. 0.3s), this test will be failed.

If you have a better solution, please share with us :)

Ref: https://gist.github.com/steveliles/11116937

VoidExplorer
  • 220
  • 1
  • 5
  • Sorry pal, I've update the link which directly link to the original author of this class – VoidExplorer Mar 04 '16 at 10:01
  • No problem, I haven't started the implementation yet. Thanks! – dany84 Mar 04 '16 at 10:18
  • Fortunately I had to change the minSdkVersion of my project to 15, so I've been able to use that class (which requires API level 14+) and it worked like a charm! Thank you! – dany84 Mar 11 '16 at 09:02
0

Override onTrimMemory(int level) in your Application. Might not be the prettiest way, but it has worked for me.

You will get

TRIM_MEMORY_BACKGROUND = 40;

when your application went into the Background.

Flo We
  • 325
  • 2
  • 12
0

You can make Application class inside your project to save state of your project. When any activity goes to pause call on pause respectively while on resume call on resume method and save state of the inside this class. Even if one activity goes on pause another on resume your class will know exact state of the application. Or another way you can save applicaton state in shared preference in each activity can change its value.

rmammadli
  • 76
  • 1
  • 7
0

i trust there is no need for u to post a code... that being said... start by logging every implemented methods onCreate(), onPause(), onDestroy(), and other well reputed Activity methods... but back button does not just pause it kills, thus onCreate is called most and check onStart() too.

Aelaf
  • 118
  • 1
  • 11
  • as said before, all the methods are called within an activity lifecycle. If the onPause or onDestroy is called in an activity it doesn't mean that the app is in background. If another activity is launched, its onStart, onResume or onCreate methods are called after the previous activity is paused/destroyed. – dany84 Mar 04 '16 at 09:20
0
public class CustomApplication extends Application {
    private static boolean activityVisible;
    @Override
    public void onCreate() {
        super.onCreate();

    }

    public static boolean isActivityVisible() {
        return activityVisible;
    }

    public static void activityResumed() {
        activityVisible = true;
    }

    public static void activityPaused() {
        activityVisible = false;
    }
}

and in your all activities set

@Override
    protected void onResume() {
        super.onResume();
        CustomApplication.activityResumed();
    }

    @Override
    protected void onPause() {
        super.onPause();
        CustomApplication.activityPaused();
    }

and in your manifest

<application
        android:name=".CustomApplication"
MPG
  • 785
  • 6
  • 20
  • I have already tried that too, but the problem is that when an activity is paused it doesn't mean that the app is in background. – dany84 Mar 04 '16 at 09:14
  • An activity pause when it is in background. http://developer.android.com/training/basics/activity-lifecycle/pausing.html#Pause – MPG Mar 04 '16 at 11:25
  • and one more thing that you have to write onPause method code in all of your activity as i suggested please read my answer. – MPG Mar 04 '16 at 11:28
  • I know that an activity is in background when it's paused, but I need to know if the whole app is in background. If an activity is paused, it could mean that you clicked on a button on that activity opening another one, so that activity is in background, but another one is alive, so the app is not in background – dany84 Mar 08 '16 at 08:05
  • So Please let me know requirenment @dany84 if you want to know about your app is in background or not, then you can know by calling it's CustomApplication class methods. :) – MPG Mar 09 '16 at 06:02
  • Which methods? There are no native methods that tell me that the app is in background. If you mean the new methods called at onPause of an activity, that doesn't work. – dany84 Mar 10 '16 at 08:40