Passing data from activity to service through interface

旧街凉风 提交于 2019-12-11 12:55:30

问题


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 Man, Has Interface) >> MQTTService (Implements Interface)

Is this possible? I cannot seem to get the String topic any further than the MQTTServiceDelegate subscribeToTopic() method, I would like to forward it to the Service now.

MQTTNotifier Activity

Here is the call I am making to a method inside MQTTServiceDelegate, and I am passing it a String topicName.

MQTTServiceDelegate.subscribeToTopic(topicName);

MQTTServiceDelegate ( Middle Man )

Here is the interface

public interface SubscribeHandler {
    public void handleSubscribe(String topic);
}

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);
      }
    }

  }

回答1:


Passing data from activity to service through interface

For getting data from Activity to service using interface we need to get interface object in Actvity which we are implementing in Service.

For example just for testing:

1. Create a static reference in Service:

public static SubscribeHandler subscribeHandler;

2. In onStartCommand() method of Service assign this to subscribeHandler:

subscribeHandler=this;

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

So for communicating between Service and Activity use LocalBroadcastManager

How to use LocalBroadcastManager?




回答2:


You can pass data from Android activity to service as intent extras while starting service.

Intent i = new Intent(this, MyService.class);
i.putExtra("key", value);
startService(i);

Inside onHandleIntent() method of your service:

@Override
protected void onHandleIntent(Intent intent) {
   String data = intent.getStringExtra(key);
   ...
}


来源:https://stackoverflow.com/questions/28611527/passing-data-from-activity-to-service-through-interface

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!