Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to receive Incoming XMPP Messages using Smack?

Tags:

I read some examples and tested them but all of them need to start a chat with someone first to receive Incoming Messages... I want to retrieve this Incoming Messages without need to talk first to the jid anyone can give an example ?

like image 945
Winter Avatar asked Feb 14 '11 16:02

Winter


2 Answers

You need to register a ChatListener to be notified of new chats, then you can add a message listener to them like normal:

connection.getChatManager().addChatListener(new ChatManagerListenerImpl());  ....  private class ChatManagerListenerImpl implements ChatManagerListener {      /** {@inheritDoc} */     @Override     public void chatCreated(final Chat chat, final boolean createdLocally) {         chat.addMessageListener(...);     }  } 
like image 97
Chris Avatar answered Nov 01 '22 12:11

Chris


i just wanted to add a copy & paste sample:

  // connect to server   XMPPConnection connection = new XMPPConnection("jabber.org");   connection.connect();   connection.login("user", "password"); // TODO: change user and pass    // register listeners   ChatManager chatmanager = connection.getChatManager();   connection.getChatManager().addChatListener(new ChatManagerListener()   {     public void chatCreated(final Chat chat, final boolean createdLocally)     {       chat.addMessageListener(new MessageListener()       {         public void processMessage(Chat chat, Message message)         {           System.out.println("Received message: "              + (message != null ? message.getBody() : "NULL"));         }       });     }   });    // idle for 20 seconds   final long start = System.nanoTime();   while ((System.nanoTime() - start) / 1000000 < 20000) // do for 20 seconds   {     Thread.sleep(500);   }   connection.disconnect(); 

This sample connects to jabber.org and displays every received message on the console.

like image 40
ManBugra Avatar answered Nov 01 '22 13:11

ManBugra