title: Cross-activity background music / detecting if an app is active or not
body: <p>I am building an android game which consists of several activities. While the app is running some background music is playing. The background music consists of several loops which are played one after another.</p>
  
  <p>So my problem is how to detect when to stop the background music. The music should stop if the user exits the app, turns off the screen or switches to another app and it should be turned back on when the user returns to my game.</p>
  
  <p>My current approach is to notify a SoundManager class which keeps track on the active activity. Every time a new activity starts (onResume) and every time an activity is ended (onStop) the SoundManager increases an internal counter. If the counter is 0 the sound is stopped and if the counter is > 0 the sound is started (if it is not already playing). </p>
  
  <p>Additionally the SoundManager listenes for ACTION_SCREEN_OFF / ACTION_SCREEN_ON events to turn the sound off/on depending on the screen state.
  This approach works quite well except for one case: If I turn off the screen sometimes (I'd say with a 50% chance) the sound starts again because apparently onResume is invoked on the activity which was active before the screen was turned off. I wonder why that happens. </p>
  
  <p>So my questions are:
  - Is there is a less fragile approach to know when to stop the background sound?
  - or is there is a workaround for the screen on/off issue.</p>
  
  <p>Thanks for your help!</p>