1

I have a service that I am using to play background music for multiple activities. Right now it plays through all the proper activities but I cannot get it to shut off when the home button is pressed. The game will close but the music is still playing. I have tried using the onUserLeaveHint method but that shuts the music off whenever I switch to a different activity. Not just when I leave the game.

Rhendar
  • 410
  • 7
  • 25

3 Answers3

1

All the activities should bind to the service. because service is alive only if one or more activities binded to it. So if no bindings to your service, then the service will be destroyed. please check this answer how to bind/unbind services. So avoid using starservice() (then you have to call stopservice() to able to distroy your service), use bindservice() to start a service - note that in this case only onCreate() will be called at your service

Community
  • 1
  • 1
laplasz
  • 3,359
  • 1
  • 29
  • 40
0

Have you considered using fragments? If you were to use fragments then you could stop the audio service in the onStop() method of the main activity. If you don't want to/can't use fragments for your app, you would have to stop the service from the onStop() of every one of your activities, or implement broadcast receivers in each of your activities: how-to-get-broadcastreceiver-for-action-android-intent-action-main-and-android

Community
  • 1
  • 1
Andrew Ogden
  • 633
  • 7
  • 17
0

Just take advantage of the fact that while transitioning from an activity to another, onStart() of the second one gets called before onStop() of the other.

Given that, along with the fact that a service bound with BIND_AUTO_CREATE flag is destroyed whenever it has no bound activities (check this other answer), you can bind to the service in any your activities onStart() method and unbind in onStop().

Whenever you have an activity transition, there will be an active bound activity, but when the current activity is backgrounded (because of home or incoming call) only onStop() will be called and thus the service will be unbounded.

Community
  • 1
  • 1
fedepaol
  • 6,834
  • 3
  • 27
  • 34