title: Android run service as long as App is in use
body: <p>I'm developing an App and I'm using a service to play background music.
  The music shall only play when the app is in use, means in foreground.
  The music shall stop when I leave app using Home button or back button (App may stay in background but is not visible -> no music).
  When I reenter the app (using home button and switch back to the app) the music shall resume too.</p>
  
  <p>My Service:</p>
  
  <pre><code>public class MusicService extends Service {
  
  MediaPlayer myPlayer;
  private final IBinder localBinder = new LocalBinder();
  
  public class LocalBinder extends Binder {
  
      MusicService getService() {
          return MusicService.this;
      }
  }
  
  @Override
  public IBinder onBind(Intent intent) {
      return localBinder;
  }
  
  public boolean onUnbind(Intent intent) {
      return true;
      // called when the last Activity is unbound from this service
      // stop your timed operations here
  }
  
  
  @Override
  public void onCreate() {
      Toast.makeText(this, "Music Service Created", Toast.LENGTH_LONG).show();
      myPlayer = MediaPlayer.create(this, R.raw.ost);
      myPlayer.setLooping(true); // Set looping
  }
  
  @Override
  public void onDestroy() {
      Toast.makeText(this, "Music Service Stopped", Toast.LENGTH_LONG).show();
      myPlayer.stop();
  }
  
  @Override
  public void onStart(Intent intent, int startid) {
      Toast.makeText(this, "Music Service Started", Toast.LENGTH_LONG).show();
      if(!myPlayer.isPlaying())
          myPlayer.start();
  }
  </code></pre>
  
  <p>}</p>
  
  <p>I'm also using a parent class for all activites. In that parent class I want to stop the Service on the Methods onPause() and onStop():</p>
  
  <pre><code>ComponentName topActivity = taskInfo.get(0).topActivity; 
        if(!topActivity.getPackageName().equals(getApplicationContext().getPackageName())) {
            stopService(new Intent(this, MusicService.class));
  </code></pre>
  
  <p>I start the service on my launcher activity</p>
  
  <pre><code>startService(new Intent(this, MusicService.class));
          Intent intent = new Intent(this, MusicService.class);
          bindService(intent, this, 0);
  </code></pre>
  
  <p>Now to my <strong>problem</strong>: The service does not stop when I press the home button, the service does not stop when I leave the app (back button).
  When I kill the task of the app, the Service starts after a few seconds again and the music will run till I force the app in settings to stop the service or uninstall the app.</p>
  
  <p>So how to shut down the service completely, when the app is in not visible background or closed? I've been through several threads here, youtube videos, tutorials and tried a lot. I also tried non-service solutions but I could not solve the problem.</p>
  
  <p>Thank you!</p>