tags:

views:

649

answers:

3

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.

+2  A: 

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
I tried that, but the problem is that onStop is actually fired about 15 seconds after the new activities onStart.
FlySwat
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
Wouldn't `onPause()` be more correct for this scenario?
fiXedd
A: 

I believe you could use:

onWindowsFocusChanged(boolean hasFocus)

from your Activity.

rcabaco
+6  A: 

I have written a utility method for this, it's part of the Droid-Fu library and BetterActivity.

Use it like this:

protected void onPause() {
    if (isApplicationBroughtToBackground()) {
       ...
    }
}

Some introductory articles about Droid-Fu on my blog.

Matthias
PS: this method inspects the current activity stack, hence (last time I checked) you must require the android.permission.GET_TASKS permission in your manifest.
Matthias
After days of trying to figure how to get the tasks, this is perfect. Massive thanks.
FlySwat
you're welcome :)
Matthias
Oh man, Droid-Fu looks great. Thanks.
fiXedd