Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Should a MediaPlayer run in separate thread?

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

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

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:

"Caution: A service runs in the main thread of its hosting process—the service does not create its own thread and does not run in a separate process (unless you specify otherwise). This means that, if your service is going to do any CPU intensive work or blocking operations (such as MP3 playback or networking), you should create a new thread within the service to do that work. By using a separate thread, you will reduce the risk of Application Not Responding (ANR) errors and the application's main thread can remain dedicated to user interaction with your activities."

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?

like image 474
smult Avatar asked Mar 27 '13 12:03

smult


People also ask

Does service run on separate thread Android?

Service runs in the main thread of its hosting process; the service does not create its own thread and does not run in a separate process unless you specify otherwise.

Why should you not perform a network operation on the main thread?

All Android apps use a main thread to handle UI operations. Calling long-running operations from this main thread can lead to freezes and unresponsiveness. For example, if your app makes a network request from the main thread, your app's UI is frozen until it receives the network response.

What is the main thread in Android?

Main Thread: The default, primary thread created anytime an Android application is launched. Also known as a UI thread, it is in charge of handling all user interface and activities, unless otherwise specified. Runnable is an interface meant to handle sharing code between threads. It contains only one method: run() .


1 Answers

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.

like image 170
ajacian81 Avatar answered Oct 11 '22 18:10

ajacian81