I'm having working code but my solution doesn't seem optimal. My question is if there exists a comon design pattern for this which I could use instead.
I have 4 different Activities all doing audio playback. I have one common class (Player
) that manages the playback so when an activity wants to play it calls the one and only instance of Player
.
No matter which Activity
is currently active I want to display the same overlay view with playback info/controls etc. This I solved by create a PlayerView.xml layout which I include
in each Activity
layout.
Last I have a PlayerListener
which I register on the Player to receive playback notifications. When the PlayerListener
receives a notification it modifies the PlayerView
in the currently active Activity
(e.g. setting the playing track name in a TextView
in PlayerView
).
In order for the PlayerListener
to know which Activity
that is the currently active one it has a a method setParent(ViewGroup parent)
which each Activity
calls both at creation and in onResume
to set its own layout parent to the listener. The PlayerListener
then adds listeners for each component (e.g. Button) in the PlayerView.xml and removes the listeners for the parent from the previous Activity
.
To me it seems inefficient that I for each change between activities must add/remove a bunch of listeners, but (afaiu) since each include
creates a copy of the referenced layout, meaning the PlayerView
is unique in the layout it is included I need to do it this way (possibly skipping the removal of listeners, but that could possibly create performance issues when scaling up to more activities).
I understand I can have an Activity superclass doing this in a single place but that doesn't remove the potential issue of constantly adding/removing listeners. Is there a better, standard way of doing this?
Thanks!