24

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 ?

Flow
  • 23,572
  • 15
  • 99
  • 156
Winter
  • 1,896
  • 4
  • 32
  • 41

4 Answers4

30

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

}
Chris
  • 10,337
  • 1
  • 38
  • 46
  • 1
    @cris Smith hi ! thx for ur reply :) could please give a full example ? i'm really in trouble :S – Winter Feb 14 '11 at 17:00
  • very useful! for the info the addChatListener can be call before the login. – h3xStream Apr 22 '11 at 04:04
  • 1
    I used the same approach, but offline messages are not received in order. How can i resolve this? – Max Jul 24 '13 at 16:33
  • 1
    @Chris Smith i have created a room and added 2 users and was able to send messages to the room. Now i want to receive the messages sent by the other users ... How to acheive this ... ??? Is this possible using this api ?? – KK_07k11A0585 Aug 26 '13 at 09:53
15

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.

ManBugra
  • 1,289
  • 2
  • 14
  • 20
  • I am doing the same, but unable to receive the message. There is a blog post I explain what is going on with my code. http://www.rmwaqas.com/chat-client-using-smack/ – Waqas Feb 01 '17 at 12:32
9

Please find the following code.
Please add smack.jar & smackx.jar to your build path

import org.jivesoftware.smack.ConnectionConfiguration;
import org.jivesoftware.smack.PacketCollector;
import org.jivesoftware.smack.XMPPConnection;
import org.jivesoftware.smack.filter.AndFilter;
import org.jivesoftware.smack.filter.PacketFilter;
import org.jivesoftware.smack.filter.PacketTypeFilter;
import org.jivesoftware.smack.packet.Message;
import org.jivesoftware.smack.packet.Packet;

public class GoogleTalkDemo extends Thread{
    private XMPPConnection xmppConnection;

    public void connect(String server, int port, String s) throws Exception {
        xmppConnection = new XMPPConnection(new ConnectionConfiguration(server, port,s));
        xmppConnection.connect();
    }

    public void disconnect(){
        if(xmppConnection != null){
            xmppConnection.disconnect();
            interrupt();
        }
    }

    public void login(String username, String password) throws Exception{
        connect("talk.google.com", 5222, "gmail.com");
        xmppConnection.login(username, password);
    }

    public void run(){
        try {
            login("youtID@sample.com", "your password");
            System.out.println("Login successful");
            listeningForMessages();
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }

    public static void main(String args[]) throws Exception {
        GoogleTalkDemo gtd = new GoogleTalkDemo();
        gtd.run();
    }

    public void listeningForMessages() {
        PacketFilter filter = new AndFilter(new PacketTypeFilter(Message.class));
        PacketCollector collector = xmppConnection.createPacketCollector(filter);
        while (true) {
            Packet packet = collector.nextResult();
            if (packet instanceof Message) {
                Message message = (Message) packet;
                if (message != null && message.getBody() != null)
                    System.out.println("Received message from "
                            + packet.getFrom() + " : "
                            + (message != null ? message.getBody() : "NULL"));
            }
        }
    }

}
Samik Bandyopadhyay
  • 858
  • 1
  • 11
  • 19
  • @Samik from where you find out this smack.jar & smackx.jar file i have dolwoad smack_4_1_3.zip but i cannot found this two jar file – PankajAndroid Aug 24 '15 at 06:23
3
private MultiUserChat   muc; /* Initialize muc */

private void listeningForMessages() 
    {
        muc.addMessageListener(new PacketListener() {
            public void processPacket(Packet packet) 
            {
                final Message message = (Message) packet;

                    // Do your action with the message              
            }
        });
    }
TheMan
  • 703
  • 8
  • 11
  • Hi @TheMan Your answer helped me a lot. The above method processPacket is called when i send a message to user but if the user reply to my message then this is not geting called ?? Plz help ... – KK_07k11A0585 Aug 26 '13 at 09:55
  • It should get called. I'm not sure why it's not working for you. – TheMan Sep 01 '13 at 06:53
  • 2
    Hi @TheMan if you want the listener of group message then you should **addPacketListner** to **connection** – KK_07k11A0585 Sep 02 '13 at 04:51
  • how do you detect whether it is incoming or outgoing as it seems to be similar message object in the latest versions – Shubham AgaRwal Feb 15 '18 at 05:43