I'm building an app with notification. The app sends notification when something comes from the server. Now I want to mute the sounds for notifications when the current app is active.
IMHO, that's not a great design choice. If your UI is in the foreground, you should not have a Notification
at all, but instead update your UI to reflect whatever event occurred in the background.
So I need to know when my app is active and what activity is active now.
In a comment, njzk2 pointed to an older blog post of mine on the activity-or-notification pattern. While the pattern is still valid, using ordered broadcasts is not a great choice. You are better served using an in-process message bus (LocalBroadcastManager
, Square's Otto, greenrobot's EventBus) instead.
But the basic approach is the same regardless of communications channel: raise an event to tell your UI layer (activities and fragments) that the event occurred. Activities and/or fragments register for those events when they are in the foreground (e.g., onResume()
) and unregister for those events when they are not (e.g., onPause()
). If nothing picks up the event, have a "backstop" handler that detects this condition and performs a fallback action, like raising the Notification
.
I have three sample apps that demonstrate this using:
If you decide that you do indeed want to force the user to have to deal with your Notification
even though your UI is in foreground, and you just want a differently-configured Notification
, you will need to track for yourself which activity is in the foreground, again via onResume()
and onPause()
.