10

Like the title says, I need to detect when my app loses focus because another app is launched (Phone call comes in, or user hits Home etc).

Overriding Activity.OnStop does not work because that is called even when switching activities within my app.

FlySwat
  • 172,459
  • 74
  • 246
  • 311
  • possible duplicate of [Android, Detect when other apps are launched](http://stackoverflow.com/questions/3290936/android-detect-when-other-apps-are-launched) – Sam Oct 31 '14 at 10:03

3 Answers3

5

I believe you could use:

onWindowsFocusChanged(boolean hasFocus)

from your Activity.

3

AFAIK Android offers no facility for this. You may be able to track this yourself (e.g., if onStop() in one of your activities is called, and onStart() in another of your activities is not called within X period of time, presumably some other app's activity is in the foreground).

CommonsWare
  • 986,068
  • 189
  • 2,389
  • 2,491
  • 1
    I tried that, but the problem is that onStop is actually fired about 15 seconds after the new activities onStart. – FlySwat Dec 04 '09 at 04:45
  • 2
    That should make things easier, then. Use a static AtomicInteger to maintain a count of active activities. Set it to 0 in the static initializer. Increment it in onStart() of all your activities. Decrement it in onStop() in all of your activities. If, in onStop(), after the decrement, the value is 0, you know that you have had no activities on screen for 15 seconds and so probably are gone for a while. Personally, I'd recommend you just not worry about whatever you're worrying about, as Android is not really designed to promote application boundaries. – CommonsWare Dec 04 '09 at 05:44
  • @fiXedd no, because after onPause() onResume is called, so the counter won't be incremented as it is being incremented inside onResume() which is called after onStart(). – tony9099 Oct 28 '13 at 14:33
2

With ICS upwards this may be possible.

This is taken from the android site:

To be notified when the user exits your UI, implement the onTrimMemory() callback in your Activity classes. You should use this method to listen for the TRIM_MEMORY_UI_HIDDEN level, which indicates your UI is now hidden from view and you should free resources that only your UI uses.

Notice that your app receives the onTrimMemory() callback with TRIM_MEMORY_UI_HIDDEN only when all the UI components of your app process become hidden from the user.

See this page for full details http://developer.android.com/training/articles/memory.html

Andrew
  • 7,548
  • 7
  • 50
  • 72