Android, should I make MediaPlayer a service?
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 compl开发者_运维问答ications into the code. Or is it more efficient?
Regards, David
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).
精彩评论