MediaPlayer 应该在单独的线程中运行吗? [英] Should a MediaPlayer run in separate thread?

查看:61
本文介绍了MediaPlayer 应该在单独的线程中运行吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在构建一个从网络服务器流式传输音乐的应用程序.该应用程序具有使用 MediaPlayer 进行播放的前台服务.

I'm building an app that streams music from a web server. The app has foreground service that uses a MediaPlayer for playback.

我的代码基于这个例子:http://developer.android.com/guide/topics/media/mediaplayer.html

My code is based on this example: http://developer.android.com/guide/topics/media/mediaplayer.html

在这个例子中,除了 prepareAsync() 调用之外,没有任何东西被线程化.令我困惑的是,当我阅读有关 Service 类的信息时,我发现了以下信息:

In the example, nothing is threaded except the prepareAsync() call. What confuses me is that when I read about the Service class I find this information:

注意:服务在其托管进程的主线程中运行 - 该服务不会创建自己的线程,也不会在单独的进程中运行(除非您另行指定).这意味着,如果您的服务将执行任何 CPU 密集型工作或阻塞操作(例如 MP3 播放或网络),您应该在服务内创建一个新线程来完成这项工作.通过使用单独的线程,您将降低应用程序无响应的风险(ANR) 错误,并且应用程序的主线程可以继续专用于用户与您的活动的交互."

我问的原因是该应用程序有时(通常在失去连接时)在流式传输音频时会冻结 UI.我完全理解如果服务使 CPU 密集工作,UI 会冻结,因为活动和服务在同一线程上运行.但是,我应该期望 MediaPlayer 如此激烈吗?也就是说,它应该在单独的线程上运行吗?

The reason I'm asking is that the app some times (usually when loosing connection) freezes the UI when streaming audio. I totally understand that the UI freezes if the service is making CPU intense work, since the activity and the service runs on the same thread. But, should I expect the MediaPlayer to be this intense? That is, should it run on a separate thread?

推荐答案

不幸的是,调用 prepareAsync() 根本不足以避免 ANR 提示和您的应用程序挂起几秒钟,特别是如果您正在播放来自网络.最好的办法是将 MediaPlayer 实例放在自己的线程中,或者至少在 Handler 中执行密集调用(如 mediaplayer.start()).我已经使用 MediaPlayer 一年多了,我可以告诉你它在各种调用后肯定会挂起,具体取决于具体情况.

Unfortunately, calling prepareAsync() is simply not good enough to avoid ANR prompts and your application hanging for a few seconds, especially if you're playing a file from the network. Your best bet is to put your MediaPlayer instance in its own thread, or at the very least execute intensive calls in a Handler (like mediaplayer.start()). I've been using MediaPlayer for over a year and I can tell you it definitely hangs after various calls, depending on the circumstances.

这篇关于MediaPlayer 应该在单独的线程中运行吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆