Skip to content Skip to sidebar Skip to footer

Play Music With Background Service

I'm trying to play music with a background service. Firstly, I have a toggle button in MainActivity for playing and pausing music. I also created BackgroundSoundService just for p

Solution 1:

I'm not sure what your onPause() and onStop() are meant to do. However when you start a service for the first time using Context.startService() the onCreate() method of the service is called and then onStartCommand() is called and later when you call startService() again only the onStartCommand() is called. So for whatever reason if you want to play the sound in a service and pause that in the very same service, you need to provide the service an Action that specifies the action you want to do.

So in your activity when you want to tell the service to play the sound:

Stringaction="PLAY";
IntentmyService=newIntent(MainActivity.this, BackgroundSoundService.class);
myService.setAction(action);
startService(myService);

and to pause the sound:

Stringaction="PAUSE";
IntentmyService=newIntent(MainActivity.this, BackgroundSoundService.class);
myService.setAction(action);
startService(myService);  

and in the onStartCommand() method in your service:

if (intent.getAction().equals("PLAY")) {
    // resume the sound
}
if (intent.getAction().equals("PAUSE")) {
    // pause the sound
}

and when you really need to stop the service meaning Destroy the service, call context.stopService() and only then onDestroy() method is called and the service is really destroyed.

Solution 2:

To prevent playing in background override on Activity pause then pause you service there and to resume where you left of save the current position in a preference then retrieve it when needed

Post a Comment for "Play Music With Background Service"