Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MediaPlayer in separate thread using Service or IntentService

Hi I need a MediaPlayer instance to run in background so I started using a Service.

Everything works fine but I get ANR (application not responding) after a while, even if the UI works perfectly. Fair enough, I do know Services are still running on the main thread so the ANR makes sense.

So I tried using IntentService, which should spawn its own thread but I got nothing but headaches. IntentService seems ok when the workers are independent but that's not the case here because I need to call the startService(intent) method from the main app each time I need to change track and I don't want to end up with multiple MediaPlayer instances that play on top of each other..

I also saw a hint suggesting using a Thread inside a Service. how to I do that with Media Player? Should the DECLARATION be in that thread or just the "prepare/start, etc"? Fromwhat I saw that doesn't seem to work but I might just implemented it wrong

Any hints is very appreciated, possibly with a very simple example.

cheers

like image 763
Lele Avatar asked Oct 26 '12 12:10

Lele


1 Answers

I strongly recommend you read the training documentation here: http://developer.android.com/guide/components/services.html

This was really helpful for me. And then the NPR app which streams audio is open source, so check out their service here: http://code.google.com/p/npr-android-app/source/browse/Npr/src/org/npr/android/news/PlaybackService.java

Reading both of those, I'd recommend using a Service and handling the threads yourself. I haven't worked with IntentService yet, but from your experience it seems like it's the wrong class to deal with music streaming. Hope that helps!

like image 180
shoke Avatar answered Oct 15 '22 17:10

shoke