Android Question How to detect when my app switches from foreground to background and back?

JohnC

Expert
Licensed User
Longtime User
One feature I am adding to my app is an overlay launch icon/button using the overlay lib from this great toolkit (https://www.b4x.com/android/forum/threads/probundle-chargeable.58754/#content). This allows my app to display a floating icon on every screen of the phone even if my app is not in the foreground, and it will allow the user to jump right back to my app from anywhere on the phone.

But, obviously when my app is in the foreground, there is no need for this icon to be visible, so I would like to hide it. I can put in code into *each* activity's "Activity_Resume" that will hide the icon, but I was wondering if there was a more global/graceful way to simply detect when any of my app's activities are now in the foreground without having to add code to each activity.

Alternatively, if my app is running and the user switches away from it (either on purpose by pressing the home button, or by surprise because some other app popped to the foreground like an incoming call), then I'd like to know this so I could then display my app's floating icon. But, again I was wondering if there was a more global/graceful way of detecting when my entire app goes to background (regardless which activity was being shown) without having to place code in each activity_pause event - so I will know when to re-display the floating icon. (because if I use the method of adding code to each activity, this will get messy because under normal operation when my app switches from one activity to another, the leaving activity will invoke a pause event, and the new activity will do a resume event - and I don't want the icon flashing on then off briefly between these events. So I'll have to add a timer and then this solution becomes messy and prone to timing-induced issues).
 
Top