-->

How to design activity-service interaction for a s

2019-02-07 11:56发布

问题:

I am an Android newbie and I wanna create a simple mp3 player. Now, as far as I understood, good way to do this would be to have a service which would be in charge of MediaPlayer class, and an activity which would represent some sort of UI and also send playing instructions to the service (play, stop, next, etc).

My question is what approach to use for activity-service communication? I tried figuring out these examples, but I don't see how I can implement pause song, next, previous etc. features of the player.

So I am just interested in concept and maybe some useful links which would guide me a little. Thanks!

回答1:

Step #1: Implement a Service.

Step #2: Have the activity send commands to the service in the form of Intents delivered via startService() (except for "stop", which would be a call to stopService()).

Step #3: Have the service handle those commands in onStartCommand() by making appropriate calls on MediaPlayer (be sure to use prepareAsync()).

Here is a trivial little example of this, for play and stop, with stubbed-out actual media usage. Here is a slightly more sophisticated example of this, using a Notification and startForeground() to ensure the player can keep playing.