0

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!

jola
  • 977
  • 2
  • 10
  • 31

2 Answers2

0

Standart pattern for this is using fragments.

Lamorak
  • 10,957
  • 9
  • 43
  • 57
  • I thought fragments would have the same issue of adding/removing listeners when they are shared between different activities, but maybe I've misunderstood that..? – jola Mar 15 '15 at 06:35
0

Ok, after reading up more on Fragments I now think I understand that there aren't any common pattern in Android for what I try to acheive. Indeed I can add the same fragment to multiple activities but each fragment becomes a new instance and just lives in the scope of the Activity, passing state info between the fragments is just like doing it for Activities.

So, each Fragment instance needs to have listeners added if they are to listen to e.g. events from a Service, unfortunately you cannot have a single Fragment instance that lives across multiple Activities. Which I would have understood if I had found this thread upfront: Retain Fragment state between Activities

Community
  • 1
  • 1
jola
  • 977
  • 2
  • 10
  • 31