0

I have a service class that receives a message. Here is the code -

public void processJSONMessage(String data) throws IOException {
            ObjectMapper objectMapper = new ObjectMapper();
            TextMessage textMessage = objectMapper.readValue(data, TextMessage.class);
            textMessageString = textMessage.getMessage();
}

Now I need to send this textMessageString to MAinActivity and display a toast message. I want to use the event bus for the same. I have already registered and unregistered the event bus in MAinActivity. But I really dont know how to use the event bus for my example. Can anyone help me please?

1 Answers1

0

Which library are you using for your EventBus?

If you want to push an event from your extended Service class you will need to grab an instance of the EventBus and post it from there. For example using Greenbot, you do something like

public void processJSONMessage(String data) throws IOException {
    ObjectMapper objectMapper = new ObjectMapper();
    TextMessage textMessage = objectMapper.readValue(data, TextMessage.class);
    textMessageString = textMessage.getMessage();
    EventBus.getDefault().post(new MessageEvent(textMessageString));
}

where MessageEvent class is just a POJO that takes in a string (refer to quick start guide). Your MainActivity (assuming you have registered in onCreate) will be able to listen to the events by creating a function like this:

@Subscribe
public void onMessageEvent(MessageEvent event){
    //Get the message string, i.e.: event.getMessage()
}
Bundeeteddee
  • 724
  • 11
  • 19