In my Android app I want to be able to play some audio in the background. I figured using a MediaPlayer in a service should be just what I need. So I created a service pretty much following Google’s example code on the Android developer website. However, my problem is that whenever a new activity is started that tries to bind to the service, a new service is started (or at least onCreate is being re-called). I’ve read through the docs and what I’m doing should be completely legal. Can anyone provide some further insight? Thanks!
public class PlayerService extends Service implements MediaPlayer.OnPreparedListener, MediaPlayer.OnErrorListener, MediaPlayer.OnBufferingUpdateListener {
public class PlayerBinder extends Binder {
PlayerService getService() {
return PlayerService.this;
}
}
private final IBinder mBinder = new PlayerBinder();
public IBinder onBind(Intent intent) {
return mBinder;
}
and from my activity I bind to a service from onCreate
private void doBindService() {
this.bindService(new Intent(this, PlayerService.class), connection, Context.BIND_AUTO_CREATE);
}
When you use
bindServiceyourServiceis created and tied to the lifecycle of yourActivity. That means when yourActivityis destroyed, so is yourService.If you want your
Serviceto remain started you must first callstartService(Intent). You could for example call this in your applicationsonCreate().After that, you can still bind to your
Serviceand when you unbind it will remain started until Android decides to kill your process or if you callstopService(Intent)orstopSelf()from somewhere in your code.For better results, and having uninterrupted music playback you should set your
Serviceto run in foreground mode (see this).Keep in mind that it will STILL be possible for Android to kill your process and stop the music playback, but if you are in foreground mode the chances are very very slim.