如何在不使用 createChat 的情况下接收消息 android XMPP 聊天 smack api

How to receive message without using createChat for android XMPP chat smack api

您好,我对在 Service 中实现 chatManagerListener 接口的逻辑感到困惑。 以下是我的服务代码:

public class MyService3 extends Service {
ChatManager chatManager;
ChatManagerListener chatManagerListener;
AbstractXMPPConnection abstractXMPPConnection;
MyXmpp2 myXmpp2;

public MyService3() {
}


@Override
public int onStartCommand(Intent intent, int flags, int startId) {
    Log.d("Myservice3:","Started");

    abstractXMPPConnection = myXmpp2.getConnection();
    abstractXMPPConnection.addConnectionListener(new ConnectionListener() {
        @Override
        public void connected(XMPPConnection connection) {
            Log.d("XMPPConnection:","connected");
        }

        @Override
        public void authenticated(XMPPConnection connection, boolean resumed) {
            Log.d("XMPPConnection:","authenticated");
            //Once authenticated start listening for messages






        }

        @Override
        public void connectionClosed() {
            Log.d("XMPPConnection:","connectionClosed");
        }

        @Override
        public void connectionClosedOnError(Exception e) {
            Log.d("XMPPConnection:","connectionClosedOnError");
        }

        @Override
        public void reconnectionSuccessful() {
            Log.d("XMPPConnection:","reconnectionSuccessful");

        }

        @Override
        public void reconnectingIn(int seconds) {
            Log.d("XMPPConnection:","reconnectingIn");

        }

        @Override
        public void reconnectionFailed(Exception e) {
            Log.d("XMPPConnection:","reconnectionFailed");

        }
    });



    Log.d("isOnline:", myXmpp2.getConnection().isConnected() + "");
    chatManager = ChatManager.getInstanceFor(abstractXMPPConnection);
    chatManager.addChatListener(chatManagerListener);
    chatManagerListener = new ChatManagerListener() {
        @Override
        public void chatCreated(Chat chat, boolean createdLocally) {

            chat.addMessageListener(new ChatMessageListener() {
                @Override
                public void processMessage(Chat chat, Message message) {

                    Log.d("Hello::","World");
                   //NOT WORKNIG
                    if(message.getBody()!=null)
                    {
                        Log.d("Message::",message.getBody());
                    }
                }
            });
        }
    };





    return super.onStartCommand(intent, flags, startId);
}



}

每当发送数据包时,我都会收到以下异常。我不知道它为什么会出现

Exception in packet listener java.lang.NullPointerException: Attempt to invoke interface method 'void org.jivesoftware.smack.chat.ChatManagerListener.chatCreated(org.jivesoftware.smack.chat.Chat, boolean)' on a null object reference
                                                                                       at org.jivesoftware.smack.chat.ChatManager.createChat(ChatManager.java:255)
                                                                                       at org.jivesoftware.smack.chat.ChatManager.createChat(ChatManager.java:287)

简单来说,我想知道如何在 service.Please 中实现 ChatMessage 侦听器

成功连接并通过身份验证后,您需要创建聊天

获得 ChatManager 的实例后。对于包传输,您需要 createchat 和 peer/group 检查 this link 创建聊天的方法。

 chatManager = ChatManager.getInstanceFor(abstractXMPPConnection);

newChat = chatmanager.createChat(userid, chatManagerListener);  

获得 Chat 实例后,您可以发送包裹并在 chatmanagerListner

上检索

newChat 你可以 sendMessage

To get Package (message, chat)

如果您的 connection/authentication 过程比

成功完成,您可以尝试下面的代码
final Chat newChat = ChatManager.getInstanceFor(xmppConn).createChat(userJid, new MessageListener() {
    @Override
    public void processMessage(final Chat arg0, final Message arg1) {
      LOG.info("Sent message: " + arg1.getBody());
    }
  });
  try {
    final Message message = new Message();
    message.setFrom(chatProperties.getDomain());
    message.setTo(userJid);
    message.setType(Type.normal);
    message.setBody(text);
    message.setSubject("");
    newChat.sendMessage(message);
    xmppConn.disconnect();
  } catch (final Exception e) {
    LOG.error("Error while sending message to " + userName + ": ", e);
  }

更新

您可以尝试使用 PacketListener

XMPPConnection 的 addPacketListener 方法 check this link for details.

将 PacketListener 添加到具有 PacketFilter 类型 Message

的 XMPPConnection

但是在添加 packetlistner 之前,如果已经在 xmppconnection 中添加了任何实例,则删除。

检查下面的代码

private PacketListener packetListener = new PacketListener() {
        @Override
        public void processPacket(Packet packet) {
            if (packet instanceof Message) {
                Message message = (Message) packet;
                String chatMessage = message.getBody();
            }
        }
    };

    private void regiSterPackateListner() {
        PacketTypeFilter filter = new PacketTypeFilter(Message.class);
        try {
            if (packetListener != null) {
                //Avoid adding multiple packetlistner
                abstractXMPPConnection.removePacketListener(packetListener);
            }
            abstractXMPPConnection.addPacketListener(packetListener, filter);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

参考这个例子:

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"));
            }
        }
    }
}

希望对您有所帮助。

关于发送和接收消息的简单演示:

import org.jivesoftware.smack.Chat;
import org.jivesoftware.smack.ChatManager;
import org.jivesoftware.smack.ChatManagerListener;
import org.jivesoftware.smack.ConnectionConfiguration;
import org.jivesoftware.smack.MessageListener;
import org.jivesoftware.smack.XMPPConnection;
import org.jivesoftware.smack.XMPPException;
import org.jivesoftware.smack.packet.Message;

public class Test {
    public static void main(String args[]) throws XMPPException {
        ConnectionConfiguration config = new ConnectionConfiguration("127.0.0.1", 5222);    
        XMPPConnection connection = new XMPPConnection(config); 
        connection.connect();   
        connection.login("userx", "123456");
        ChatManager cm = connection.getChatManager(); 
        Chat chat = cm.createChat("tongqian@tsw-PC", null);
        /*
         * add listener
         */
        cm.addChatListener(new ChatManagerListener() {
            @Override
            public void chatCreated(Chat chat, boolean create) {
                chat.addMessageListener(new MessageListener() {
                    @Override
                    public void processMessage(Chat chat, Message msg) {
                        System.out.println(chat.getParticipant() + ":" + msg.getBody());
                    }
                });
            }
        });
        chat.sendMessage("hello");  
        while(true);        
        //connection.disconnect();  
    }
}