1

I am making an android game and I have a service that plays background music. I use two buttons to start and stop the music from the Title/Menu activity. The problem I am having is that if the music is left on when ever you receive a call or exit the app the music is still playing until you go to the app and turn it off.

Cœur
  • 37,241
  • 25
  • 195
  • 267
Manji
  • 137
  • 9
  • 1
    So what do the buttons do? Can't you just recreate this behavior in the appropriate `onPause` method? – slhck May 31 '11 at 21:41
  • One starts the music and the other stops the music. I am not sure how I would do that. – Manji May 31 '11 at 22:49
  • 1
    Well you have `onPause` in your Game activity. There, insert the relevant code that you use to stop the music. – slhck Jun 01 '11 at 09:06

2 Answers2

1

The best way to do this would be to send a command to stop the music in the onPause() or onStop(). It seems like you already know how to stop the music, per your comments. You'll need to start the music in the corresponding command as well. I'd recommend using onPause(). See the lifecycle of an activity.

PearsonArtPhoto
  • 38,970
  • 17
  • 111
  • 142
  • I have a onPause() and a onStop method inside of the service, I was thinking of putting one in side of the activity itself. But I am not sure how I would do that since I call the service through the buttons. – Manji May 31 '11 at 22:55
1

If you still want to play music in the Service, then you need to communicate from the Activity (where you get to know about lifecycle events) to the Service (where the music can be played/stopped).

In Android, you do this by means of binding the Service to an Activity. See e.g. Bound Services, or many many others articles on the web (e.g. here).

The idea behind is that you create a class/object with a custom API. This object can be used by the Activity code. When you invoke methods on this API, Android would actually dispatch this calls to the Service. In this way, you start a Service somewhere in your code, and later you can get hold of it by working with its Binder.

HTH

superjos
  • 12,189
  • 6
  • 89
  • 134