views:

51

answers:

2

I'm trying to write an Android application which will allow users to listen to a radio station.

I have got the start and stop buttons to work and it plays the stream. If I press the home key and start doing other bits and pieces with the phone, the stream continues to play. This is how I want it to work.

Should I bother creating a service to play the stream, or is the method I already use good enough? What benefit would having it in a service bring? A lot of tutorials and examples online seem to use services but it seems to me it's just adding extra complications into the code. Or is it more efficient?

Regards, David

A: 

You don't need to use a service, but your users may under normal use find that playback stops unexpectedly, it depends on the normal use case, so a Service is the best approach.

The reason is due to the lifetime of the Activity that your streaming object / media player is currently attached to.

At some point the system will completely release the Activity now that it is no longer visible to the user, and once GC happens playback will stop. This will happen depending on memory pressure and what other actions the user takes, such as launching other apps. Services are allowed a longer life span, in general they will be released only after all other backgrounded activities are released but before the foreground activity. A more complete description of process lifecycle rules around Services can be found in the Android docs here.

You may also want to look at the PowerManager and the use of PARTIAL_WAKE_LOCK, which would allow playback to continue when the handset would normally sleep (at the cost of battery life).

cistearns
A: 

Decoupling the UI from the player is important. It avoids additional work later down the road when you need to receive phone calls, or need to restart the player (and only the player, not the entire activity) when it crashes.

Also, don't assume that your customers will have phones that have as much memory/hardware/etc as yours. Even if you did get everything working on your phone consistently, which I doubt, assuming that your app will work on everyone else's Android phone just as consistently (without following Android's best practices) is quite the leap of faith.

Stephan Branczyk