开发者

How do I stop playing audio when the home button is pressed?

My application always runs a backgro开发者_运维知识库und audio in services. When I click the home button, the control comes back to home screen but the audio keeps on playing.

So, how can I stop playing audio when I click the home button?


If the audio is being played by a Service, then it won't be affected if an Activity is being destroyed. That is exactly the purpose of separating it into a Service.

If you want it to be dependent on your UI, then move the play to the Activity instead. It will stop when the Activity finishes. Alternatively, you can send a message to the Service in order to stop the music.

See the dev guide for more details: http://developer.android.com/guide/topics/fundamentals/bound-services.html


Your activity can override onPause() and/or onWindowFocusChanged() to detect that you're no longer running or on top of the display. These are good places to stop playing audio that isn't intended to be playing if the activity isn't visible, you just have to be careful about switching to other activities within your application.


Override onPause() and resume it on onResume().

Why you play the music on Service?

In that case, use bindService() and unbindService(). So the Service can respond to onDestroy() when Activity call unbindService().

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜