powered by Jive Software

Smack ChatManager how to listen incoming messages

I am using Smack 4.1.3 and Openfire. I can use addAsyncStanzaListener to receive Message (below).

// Add a packet listener to get messages sent to us
StanzaFilter filter = new StanzaTypeFilter(Message.class);
connection.addAsyncStanzaListener(new StanzaListener() {
      @Override
      public void processPacket(Stanza packet) {
           Message message = (Message) packet;
           if (message.getBody() != null) {
                   //String fromName = StringUtils.parseBareAddress(message.getFrom());
                  String fromName = message.getFrom();
                  Log.i("XMPPChatDemoActivity ", " Text Recieved " + message.getBody() + " from " + fromName);
          }
     }
}, filter);  

After reading examples, most of them are using ChatManager. My questions are

  1. Is it a better way to use ChatManager to manager chat and sending/receiving messages?

  2. In most example, a createChat with a target username is being used. If I am not the one who initiates the message, I don’t have any username can be passed to the createChat method. Can you show me the code for ChatManager listening to new incoming messages (that are not initiated by me).

Chat chat = ChatManager.getInstanceFor(connection).createChat("jsmith@jivesoftware.com", new MessageListener(){

  • public void processMessage(Chat chat, Message message){*

  • System.out.println("Received message: " + message);*

  • }*

});

chat.sendMessage(“Hello”);

Thank you!

In your example you could use the MessagesWithBody filter to skip the message.getBody() check.

  1. Is it a better way to use ChatManager to manager chat and sending/receiving messages?

ChatManager does a bit of extra logic (see the source), but both methods are more or less equal.

  1. In most example, a createChat with a target username is being used. If I am not the one who initiates the message, I don’t have any username can be passed to the createChat method. Can you show me the code for ChatManager listening to new incoming messages (that are not initiated by me).

See javadoc of ChatManager.

1 Like

This topic was automatically closed 62 days after the last reply. New replies are no longer allowed.