How to send data from service to activity?

2019-03-02 11:47发布

问题:

I'm beginner in Android development. I try to create kind of MusicPlayer, which uses Service for playing music. When I click buttons in MainActivity, I call startService with Intent, which includes signal for action, such as play, pause, stop, etc... But I want to send data back from service to activity. For example, when current track has stopped and begin to play the next one, MainActivity got to receive track name and author name. Or when last track in the playlist is stopped, button "Pause" on the Activity got to changed to "Play". I need to send data as map. Like "title: value", "playing: false". So, what I tried. At first PendingIntent. I create it in the Activity and send by startService to the Service. I need to specify request code in PendingIntent, sting action in Intent for this PendingIntent. I don't know, how to use it. Then I tried bindService. But Service send data only if Activity request it. Another examples I didn't find.

Which way is most simple to send data from Service to Activity?

回答1:

Use a messenger to send the Message from the Service on onHandleIntent() method, then Recieve it with A handler...see this tutorial http://www.vogella.com/articles/AndroidServices/article.html



回答2:

You can use an BroadcastReceiver and set as message play,stop,pause...etc, here are some tutorials whit brodcastreceiver :

BrodcastReceiver link 1
BrodcastReceiver link 2
BrodcastReceiver link 3