我正在使用Android的应用程序。我有一个Service
来管理流的后台进程。然后我有一个对象AudioPlayer
来管理MediaPlayer
实例并从服务中调用它。但我遇到的问题是听众onPrepared
,因为它在我的AudioPlayer
内,但我需要它在触发时从我的对象AudioPlayer
向我的Service
发送消息。这可能吗?
我可以尝试将MediaPlayer
的逻辑放在Service
之内,但我想让事情解耦。
答案 0 :(得分:0)
是的可能。对于服务和片段之间的通信,您可以使用 1.BroadCast Receiver或2.Messenger
使用信使引用此链接Communication between an Application class and Service in Android
答案 1 :(得分:0)
创建一个允许您在服务和对象之间进行通信的公共接口。
public interface MyListener {
public void receiveNotification();
}
之后,您必须使您的对象实现该接口。
public class MediaObject implements MyListener {
public void init () {
InitService.getService.addListener(this);
}
@Override
public void receiveNotification () {
//what you want to do
}
//rest of your class
为了使其成功,您应该在服务类中使用:
public class YourService extends Service {
MyListener listener;
public YourService static getService () {
return YourService.this;
}
public void addListener (MyListener listener) {
this.listener = listener;
}
public void methodYouWantToCommunicateWithObject () {
//your code
if (listener!= null) {
listener.receiveNotification();
}
}