I am writing an Android app that plays music. When the Activity is the foregroud, the media control buttons (Play, Pause, Stop, etc..) are visible. The music should keep playing when the user exits the activity. He can restart the Activity to hit the stop button later if he chooses.
At present, the instance of MediaPlayer is wrapped by a class that is a singleton:
public class MediaPlayerPresenter {
public static final String TAG = MediaPlayerPresenter.class.getSimpleName();
MediaPlayer _player;
PlayerState _state;
public MediaPlayerPresenter() {
_state = PlayerState.Idle;
_player = createMediaPlayer(); // calls new MediaPlayer and hooks up event callbacks
}
static public MediaPlayerPresenter getInstance() {
if (_staticInstance == null) {
_staticInstance = new MediaPlayerPresenter();
}
return _staticInstance;
}
// not shown - code that keeps track of MediaPlayer events, state, updating the
// view, handling view events, etc...
As it works now, the activity may get destroyed or stopped as a result of the user leaving the application, but the running process (evidently) lives on as music continues to play. When the activity is restarted or brought back to the foreground, the media controls of the view re-associate with the already running MediaPlayer via the singleton instance above.
So far, so good. But I've been reading that background music should be managed by a service. So my questions:
Why is it better to use a Service to maintain the lifetime of the MediaPlayer instance instead of a plain old singleton class? Is it because the lifetime of the singleton running in a process without an Activity or Service is not guaranteed? Or something else?
I'm ok with using a Service in lieu of a singleton. And if I understand correctly, Service and Activities of an application run in the same thread. If that's the case, when my Activity starts back up again, is it ok for it to access the the instance of the MediaPlayer class owned by the Service class directly ? I don't see much value of using a binder interface for the Activity code to to talk to a local Service in the same process.
Any good examples of a background music player using a Service pattern?