在 Android 中使用 MediaPlayer 时屏幕旋转时音乐停止
我在 Android 中遇到了一个问题,我认为我需要保留对 MediaPlayer 对象的某种引用。
在我的 Activity
中,我首先实例化 MediaPlayer
对象,然后我可以开始播放所选的音乐。问题在于,当屏幕旋转时,活动被销毁,再次创建,然后我失去了对 MediaPlayer 的引用(因为我无处保存它)。创建一个新对象,下次用户与手机交互时,音乐将停止播放。保持手柄的正确方法是什么?我应该这样吗?它不可序列化,因此我无法将其放入 onSaveInstanceState(Bundle)
中。
感谢您的帮助。
I am running into an issue in Android
where I think I need to keep some sort of reference to a MediaPlayer
object.
In my Activity
I begin by instantiating the MediaPlayer
object and I can begin playing chosen music. The problem lies when the screen rotates, the Activity gets destroyed, created again, and then I lose reference to the MediaPlayer (since nowhere do I save it). A new object gets created and the next time the user interacts with the phone, the music stops playing. What is the proper way of keeping a handle on it? Should I be? It's not Serializable so I can't put it in a onSaveInstanceState(Bundle)
.
Thanks for the help.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
我会尝试将 MediaPlayer 放入服务中,设置绑定并在应用程序中控制它。
I would try putting the
MediaPlayer
in a service, setting up a bind and control it from withing your application.我也有同样的问题。由于我并不真正需要旋转屏幕,因此我将
android:screenOrientation="portrait"
添加到清单文件中的 Activity 中。I also had the same problem. Since I didn't really need the screen to rotate, I added
android:screenOrientation="portrait"
to the activity in the manifest file.