如何使用Smack接收传入的XMPP消息?

时间:2011-02-14 16:46:58

标签: xmpp smack

我阅读了一些示例并对其进行了测试但是所有这些示例都需要首先与某人开始聊天以接收传入消息...我想要检索此传入消息而无需先与jid交谈,任何人都可以举例说明?

3 个答案:

答案 0 :(得分:29)

您需要注册一个ChatListener才能收到新聊天的通知,然后您可以像平常一样添加消息监听器:

connection.getChatManager().addChatListener(new ChatManagerListenerImpl());

....

private class ChatManagerListenerImpl implements ChatManagerListener {

    /** {@inheritDoc} */
    @Override
    public void chatCreated(final Chat chat, final boolean createdLocally) {
        chat.addMessageListener(...);
    }

}

答案 1 :(得分:15)

我只想添加一份副本&粘贴样本:

  // 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();

此示例连接到jabber.org并在控制台上显示每个收到的消息。

答案 2 :(得分: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              
            }
        });
    }