按下主页按钮时如何停止播放音频?
我的应用程序始终在服务中运行背景音频。当我单击主页按钮时,控件返回主屏幕,但音频继续播放。
那么,如何在单击主页按钮时停止播放音频呢?
My application always runs a background 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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
如果音频正在由
Service
播放,那么即使Activity
被销毁,它也不会受到影响。这正是将其分离为服务的目的。如果您希望它依赖于您的 UI,请将播放移至 Activity。当 Activity 完成时它将停止。或者,您可以向服务发送消息以停止音乐。
有关更多详细信息,请参阅开发指南:http://developer.android.com /guide/topics/fundamentals/bound-services.html
If the audio is being played by a
Service
, then it won't be affected if anActivity
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
您的 Activity 可以重写 onPause() 和/或 onWindowFocusChanged() 以检测您不再运行或位于显示屏顶部。如果活动不可见,这些是停止播放不打算播放的音频的好地方,您只需小心切换到应用程序中的其他活动即可。
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.
覆盖
onPause()
并在onResume()
上恢复它。为什么在
Service
上播放音乐?在这种情况下,请使用
bindService()
和unbindService()
。因此,当Activity
调用unbindService()
时,Service可以响应onDestroy()
。Override
onPause()
and resume it ononResume()
.Why you play the music on
Service
?In that case, use
bindService()
andunbindService()
. So the Service can respond toonDestroy()
whenActivity
callunbindService()
.