How to stop Service when app is paused or destroyed but not when it switches to a new Activity? <p>Currently I have a <code>Service</code> which I am using to play a sound file in the background whilst the app is open:</p> <pre><code>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(); } } </code></pre> <p>And the <code>Service</code> is started in my <code>MainActivity</code> like so:</p> <pre><code>BackgroundSoundService backgroundSoundService = new Intent(this, BackgroundSoundService.class); </code></pre> <p>I want the <code>Service</code> 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 <code>onPause</code> and <code>onDestroy</code>, and implement this line:</p> <pre><code>stopService(backgroundSoundService); </code></pre> <p>However when I then switch to another <code>Activity</code>, <code>onPause</code> is then triggered and the <code>Service</code> stops. How can I ensure that the <code>Service</code> continues to run as long as the application is open in the foreground but stops when the app is minimised or closed?</p>