开发者

Stopping Background Music When App is destroyed

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 lef开发者_如何学Pythont 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.


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.


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

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜