通过接口将数据从活动传递到服务 [英] Passing data from activity to service through interface
问题描述
我正在尝试将数据从Android活动传递到服务。我试图通过调用包含接口的另一个类中的方法来实现,该接口由服务实现。
I am trying to pass data from an Android Activity to a Service. I am attempting to do so by calling a method within another class which contains an interface,this interface is implemented by the Service.
MQTTNotifier(Activity)>> MQTTServiceDelegate(Middle男人,有接口)>> MQTTService(Implements Interface)
MQTTNotifier(Activity) >> MQTTServiceDelegate(Middle Man, Has Interface) >> MQTTService (Implements Interface)
这可能吗?我似乎无法获得比MQTTServiceDelegate subscribeToTopic()方法更多的String主题,我现在想将它转发给服务。
MQTTNotifier活动
这是我对MQTTServiceDelegate中的方法进行的调用,我传给它一个String topicName。
Here is the call I am making to a method inside MQTTServiceDelegate, and I am passing it a String topicName.
MQTTServiceDelegate.subscribeToTopic(topicName);
MQTTServiceDelegate(中间人)
这是接口
public interface SubscribeHandler {
public void handleSubscribe(String topic);
}
这里我试图获取String主题,并将其传递给界面,我希望服务接收并做一些事情。
Here I am attempting to take the String topic, and pass it to the interface, which I would like the Service to receive and do something with.
public static void subscribeToTopic(String topic) {
SubscribeHandler subscribeHandler = new SubscribeHandler() {
@Override
public void handleSubscribe(String topic) {
// TODO Auto-generated method stub
// WHAT DO I DO HERE?
}
};
}
MQTTService
这是服务中的接口方法实现
This is the interface method implementation inside the Service
@Override
public void handleSubscribe(String topic) {
// TODO Auto-generated method stub
if (isOnline()) {
if (connectToBroker()) {
Log.e("SUBSCRIBE TO ANOTHER TOPIC", "SUBSCRIBE TO ANOTHER TOPIC");
subscribeToTopic(topic);
}
}
}
推荐答案
通过接口将数据从活动传递到服务
Passing data from activity to service through interface
用于从中获取数据使用我们在Service中获取接口对象的接口的服务活动,我们正在Service中实现。
For getting data from Activity to service using interface we need to get interface object in Actvity which we are implementing in Service.
例如,仅用于测试:
1。创建静态参考服务:
public static SubscribeHandler subscribeHandler;
2。在 onStartCommand()
服务方法将此分配给subscribeHandler:
2. In onStartCommand()
method of Service assign this to subscribeHandler:
subscribeHandler=this;
现在,在Activity中启动服务访问 subscribeHandler
来自发送数据的服务:
Now after starting Service access subscribeHandler
in Activity from Service for sending data:
subscribeHandler.handleSubscribe("Message");
但不是很好的方法使用静态对象在应用程序组件之间发送数据
But not good approach use static objects for sending data between to components of application
因此,对于服务和活动之间的通信,使用 LocalBroadcastManager
So for communicating between Service and Activity use LocalBroadcastManager
这篇关于通过接口将数据从活动传递到服务的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!