Android中发送的活动命令服务命令、Android

2023-09-12 22:21:58 作者:烟嗓

我有一个活动类,并在它的内部有媒体播放器的服务。用户从他们想玩SD卡中的MP3。予使用意向额外从活动到服务发送的mp3的路径。

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.

在服务的媒体播放器可以开始和播放用户选择的MP3。但是一个问题。如果用户presses暂停按钮媒体播放器应暂停,之后又在同一位置,这是暂停在恢复的歌曲。如何从活动到该服务发送命令这首歌应该暂停?

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?

这是很容易把媒体播放器实例中的活动内。这样我就可以把一个onclick监听器,并有一个按钮。随着媒体播放器的服务运行外部的活动,不能老是只把屏幕上的一个按钮,让他们推动暂停。

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.

推荐答案

有两个选项:

如果你的服务是本地服务(这应该是这里的情况),你可以绑定的活动和服务。请参阅服务类文档有关如何做到这一点的例子

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

您也可以使用广播。基本上,你将有一个广播听众在你的服务,将期望广播的操作,如com.mypackage.mediaplayer.Stop,com.mypackage.mediaplayer.Pause,com.mypackage.mediaplayer.Next,.. 。您的活动则只需发出了正确的广播消息单击按钮时。

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.

您也应该看看在机器人股票的音乐播放器源$ C ​​$ C 。

已经做了同样类型的项目,我会建议去与选项#2。

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