FlySwat
FlySwat

Reputation: 175643

Android: Detect when another Activity is launched (or your activity loses focus)

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.

Upvotes: 10

Views: 11327

Answers (3)

Andrew
Andrew

Reputation: 8110

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

Upvotes: 2

user139992
user139992

Reputation:

I believe you could use:

onWindowsFocusChanged(boolean hasFocus)

from your Activity.

Upvotes: 5

CommonsWare
CommonsWare

Reputation: 1007276

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).

Upvotes: 3

Related Questions