Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do Android mediaplayers continuing playing songs when app is closed?

Wondering how next songs are played once app is closed as if playing an entire CD or playlist...

like image 238
Metallicraft Avatar asked Jul 12 '11 17:07

Metallicraft


1 Answers

The media player only plays one audio track. What media players do, is listen on the onCompletion event and play the next track.

The MediaPlayer is bound to the process, not the activity, so it keeps playing as long as the process runs. The activity might be paused or destroyed, but that won't affect the internal thread that MediaPlayer uses.

I'm building an audio player to learn Android, you can see the service that plays audio files here

edit

regarding the first comment: The service keeps running on the background and keeps running after you "exit" the application, because the lifecycle of the service and Activities are different.

In order to play the next track, the service registers a callback on the MediaPlayer so the service is informed when an audio stream completed. When the audio completes, the service cleans up the resources used by the MediaPlayer, by calling MediaPlayer.release(), and then creates a fresh new media player with the next audio track to play and registers itself to be notified again when that audio track completes, ad infinitum :).

The MediaPlayer class doesn't understand playlists, so the service is responsible for playing a track after the previous track completes.

In the AudioPlayer service I've created, an activity queues tracks in the AudioPlayer and the AudioPlayer is responsible for playing them in order.

I hope it's clear and again, if you have some time, please check the code of AudioPlayer service I've put above. It's not pure beauty, but it does its job.

like image 164
Augusto Avatar answered Oct 25 '22 11:10

Augusto