Search code examples
androidserviceandroid-activitycommunication

sending commands from Activity to Service in android


I have one activity class and a service with media player inside of it. The user selects the mp3 from the SD card that they want to play. I use Intent extra to send the path of that mp3 from the activity to the service.

In the service the Media player can start and play the mp3 that the user selected. however one problem. If the user presses the pause button the media player should pause and resume the song later in the same position that it was paused at. How do I send the command from the activity to the service that the song should be paused?

it is much easier to put the mediaplayer instance inside of the Activity. that way I can put an onclick listener and a button there. With media player run by the service it is external to the activity and can`t just put a button on the screen for them to push for pause.


Solution

  • Two options:

    1. If your service is a local service (this should be the case here), you can bind the activity and the service. See the Service class documentation for an example about how to do that

    2. You can also use broadcasts. Basically, you will have a broadcast listener in your service that will expect broadcast actions such as "com.mypackage.mediaplayer.Stop", "com.mypackage.mediaplayer.Pause", "com.mypackage.mediaplayer.Next", ... Your activity then simply sends the right broadcast message when a button is clicked.

    You should also have a look at the android stock music player source code.

    Having done the same kind of project, I would advise to go with option #2.