如果一个MediaPlayer的在单独的线程中运行? [英] Should a MediaPlayer run in separate thread?

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

问题描述

我要建一个应用程序,流音乐从Web服务器。该应用程序有一个使用的MediaPlayer播放前台服务。

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

我的code基于这个例子:<一href="http://developer.android.com/guide/topics/media/mediaplayer.html">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()调用。什么混淆我的是,当我读到的服务类,我觉得这样的信息:

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。我完全明白,UI冻结该服务是否让CPU紧张的工作,因为活动和服务,在同一线程上运行。但是,我应该会在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实例在自己的线程,或者至少是执行密集的调用都在处理程序(如 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天全站免登陆