Search code examples
javaandroidservicemedia-player

How to Stop service when app goes in background


I have a multi activity app. In the main activity a service is initiated that plays music. When I navigate through activities the music is still playing ( which is something that I want) but the music is still playing when I click home button and app goes in the background(which is something I don't want).

  1. My first solution was to do 'stopService()' onPause of main activity but this prevented the music from playing in the other activities.

  2. Tried the same in onStop method, same problem occurred.

Q: How can I stop the music(stop the service) from playing when the whole app goes in the background?

My service code:

public class MediaService extends Service {
private MediaPlayer player;

@Nullable
@Override
public IBinder onBind(Intent intent) {
    return null;
}

@Override
public int onStartCommand(Intent intent, int flags, int startId) {
    player = MediaPlayer.create(this, R.raw.music);
    player.setLooping(true);
    player.start();
    return START_STICKY;
}

@Override
public void onDestroy() {
    super.onDestroy();

    player.stop();
}

And I start/stop service with:

 music_intent = new Intent(this, MediaService.class);
 startService(music_intent);
 stopService(music_intent);

P.S. Thanks for all the answers but as I said onStop methods stops the music when I change activities which is something that I don't want.


Solution

  • Found this solution in a similar question that uses Application.ActivityLifecycleCallbacks in Application class to check when app goes in Background and then send a Broadcast to the service to stop it.

    More in: Stop MediaPlayer service when app goes in Background