Currently I have a Service
which I am using to play a sound file in the background whilst the app is open:
public class BackgroundSoundService extends Service {
MediaPlayer player;
public IBinder onBind(Intent arg0) {
return null;
}
@Override
public void onCreate() {
super.onCreate();
player = MediaPlayer.create(this, R.raw.sound);
player.setLooping(true);
player.setVolume(100, 100);
}
public int onStartCommand(Intent intent, int flags, int startId) {
player.start();
return 1;
}
@Override
public void onDestroy() {
player.stop();
player.release();
}
}
And the Service
is started in my MainActivity
like so:
BackgroundSoundService backgroundSoundService = new Intent(this, BackgroundSoundService.class);
I want the Service
to continue to run whilst the app is open, although to stop when the app is minimised or destroyed. I thought the initial solution to this would be to override onPause
and onDestroy
, and implement this line:
stopService(backgroundSoundService);
However when I then switch to another Activity
, onPause
is then triggered and the Service
stops. How can I ensure that the Service
continues to run as long as the application is open in the foreground but stops when the app is minimised or closed?