Your counter based approach is plain wrong. One reason: onStop() is not guaranted to execute.
I would assume that your notion of "background" and "foreground" should be the same as that of Android. However, when I read what you have done so far, it seems as if you have a different idea of what "background" and "foreground" mean, than Android has.
From there:
- If you have an idea of what background and foreground mean which differs from Android, you're not doing yourself a favour and probably follow a misguided path, so recosnider adjusting the meaning of foreground and background.
- Once you have the same idea as Android about background and foreground, the question is, why do you have to generate events when Android already does that. If you have to send events to a service or such, then it will be simple by listening for Activity lifecycle events and firing corresponding events for your Service.
Regarding onWindowFocusChanged: Yes, of course the notification panel can hide your App temporarily; have you used an Android device yet? The big question here is whether you would consider your App in the background then, because Android considers your App to be in the background if the notification panel is being shown.
Update: I just re-read your Q's title. Unfortunately, you're not stating what you really want/need to do, because visibility can mean a lot of things. E.g. do you consider your app to be visible if a semi transparent notification panel is laid out on top of it, or not? But the bottom line remains the same: It would be easiest if you align what you want with what Android does offer. ;)
Update 2: If you really need to know whether your Activity has been moved to the background by a popup of your own activity or by yourself, this answer here should give you the information you need.