简体   繁体   中英

How to send one to one message using smack API 4.1.0 android

I am using the code from the official documentation of smack API to send message to a specific Jabber ID.
CLick Here

I am able to receive messages from a room using below code.

   public  void joinChatRoom(){
        MultiUserChatManager manager = MultiUserChatManager.getInstanceFor(connection);
        multiUserChat = manager.getMultiUserChat("test@-mbp-9");
        try {
            multiUserChat.join("user");
        } catch (SmackException.NoResponseException e) {
            e.printStackTrace();
        } catch (XMPPException.XMPPErrorException e) {
            e.printStackTrace();
        } catch (SmackException.NotConnectedException e) {
            e.printStackTrace();
        }
        ChatManager.getInstanceFor(connection).addChatListener(new ChatManagerListener() {
            @Override
            public void chatCreated(Chat chat, boolean createdLocally) {
    chat.addMessageListener(new ChatMessageListener() {
        @Override
        public void processMessage(Chat chat, Message message) {
            System.out.println(message.getBody());
        }
    });
            }
        });
        System.out.println("Test");
    }

My Question is that how can I send message to a specific JID because i am not able to work it out even after a lot of googling what i am missing. Connection is fine user is also authenticating but below code is now working for send message.

 public void sendMsg() {
        if (connection.isConnected()) {
            // Assume we've created an XMPPConnection name "connection"._
            chatmanager = ChatManager.getInstanceFor(connection);
            newChat = chatmanager.createChat("user123@csofts-mbp-9", new ChatMessageListener() {
                @Override
                public void processMessage(Chat chat, Message message) {
                    System.out.println("Received Message:"+message);
                }
            });

            try {
                System.out.println("check the message....");
                newChat.sendMessage("Howdy!alksd;lsakdsa;lkdsa;lksa;lsa");
            } catch (SmackException.NotConnectedException e) {
                e.printStackTrace();
            }
        }
    }

Any Help will be appreciated Thanks.

Here is example of sending message code from my last project:

private void sendMessage(String body, String toJid) {
     try {
         Jid jid = JidCreate.from(toJid + "@" + MyApplication.CHAT_DOMAIN);
         Chat chat = ChatManager.getInstanceFor(mConnection)
                 .createChat(jid.asJidWithLocalpartIfPossible());
         chat.sendMessage(body);
     } catch (Exception e) {
     } 
}

UPDATE:

How to receive a message:

When you are authenticated:

ChatManager.getInstanceFor(mConnection).addChatListener(YourConnectionClass.this);

(YourConnectionClass should implement ChatManagerListener and ChatMessageListener)

Also you need to implement the methods below:

@Override
public void chatCreated(Chat chat, boolean b) {
    chat.addMessageListener(ChatConnection.this);
}

@Override
public void processMessage(Chat chat, Message message) {
    if (message.getType().equals(Message.Type.chat) || message.getType().equals(Message.Type.normal)) {
        if (message.getBody() != null) {
            Jid jid = message.getFrom();
            Localpart localpart = jid.getLocalpartOrNull();
            ...
        }
    }
}

Please follow few steps for one to one communication in xmpp: In StanzaListener you have got all message with adding connection between two person but if you want specific get two person chat then use ChatMessageListener .

Step 1. Declare as a global variables

ChatManagerListener chatListener;
ChatMessageListener messageListener;
Chat chat;
private Jid opt_jid;
StanzaListener packetListener;

Step 2. Use this code in oncreate or in fragment

Note: Make sure you have connected with chat server.

try {
        String opt_jidStr = "user_" + userid;
        try {
            opt_jid = JidCreate.bareFrom(Localpart.from(opt_jidStr), Domainpart.from(Common.HOST));
            PurplkiteLogs.logError(TAG,"opt jid :" + opt_jid);
        } catch (XmppStringprepException e) {
            e.printStackTrace();
        }
        messageListener = new ChatMessageListener() {
            @Override
            public void processMessage(Chat chat, Message message) {
                AppLogs.logInfo(TAG, "chat get me something " + message.getBody());
            }
        };

        packetListener = new StanzaListener() {
            @Override
            public void processPacket(Stanza packet) throws SmackException.NotConnectedException, InterruptedException {

                if (packet instanceof Message) {
                    final Message message = (Message) packet;

                   }
            }
        };

        chatListener = new ChatManagerListener() {

            @Override
            public void chatCreated(Chat chatCreated, boolean local) {
                onChatCreated(chatCreated);
            }
        };

       XMPP.getInstance().getConnection(acitiviy)).addAsyncStanzaListener(stanzaListener, null);
       ChatManager.getInstanceFor(XMPP.getInstance().getConnection(acitiviy)))
            .addChatListener(chatManagerListener);
        ServiceDiscoveryManager sdm = ServiceDiscoveryManager
            .getInstanceFor(XMPP.getInstance().getConnection(acitiviy)));
        sdm.addFeature("jabber.org/protocol/si");
        sdm.addFeature("http://jabber.org/protocol/si");
        sdm.addFeature("http://jabber.org/protocol/disco#info");
        sdm.addFeature("jabber:iq:privacy");


        try {
            String addr1 = XMPP.getInstance().getUserLocalPart(getActivity());
            String addr2 = opt_jid.toString();

            if (addr1.compareTo(addr2) > 0) {
                String addr3 = addr2;
                addr2 = addr1;
                addr1 = addr3;
            }
            chat = ChatManager.getInstanceFor(
            XMPP.getInstance().getConnection(acitiviy)))
            .getThreadChat(party1 + "-" + party2);
            AppLogs.logInfo(TAG, "chat value single chat :" + chat + " , " + addr2 + " , " + addr1);
            // for subscribed the user
            Presence subscribe = new Presence(Presence.Type.subscribe);
            subscribe.setTo(opt_jidStr);
             XMPP.getInstance().getConnection(acitiviy)).sendStanza(packet);
            // for subscribed the user

            if (chat == null) {
            chat = ChatManager.getInstanceFor(
            XMPP.getInstance().getConnection(acitiviy))
            .createChat(jid, party1 + "-" + party2,
                    messageListener);
                AppLogs.logInfo(TAG, "chat value single chat 1 :" + chat);
            } else {
                chat.addMessageListener(messageListener);
                AppLogs.logInfo(TAG, "chat value single chat  2:" + chat);
            }

        } catch (Exception e) {
            e.printStackTrace();
        }


    } catch(Exception e) {
        e.printStackTrace();
    }

Step 3. Methods for one to one chat purposer

  void onChatCreated(Chat chatCreated) {
    if (chat != null) {
        if (chat.getParticipant().getLocalpart().toString().equals(
                chatCreated.getParticipant().getLocalpart().toString())) {
            chat.removeMessageListener(messageListener);
            chat = chatCreated;
            chat.addMessageListener(messageListener);
        }
    } else {
        chat = chatCreated;
        chat.addMessageListener(messageListener);
    }
}


void sendMessage(String message) {
    if (chat != null) {
        try {
            chat.sendMessage(message);

        } catch (SmackException.NotConnectedException e) {
        } catch (Exception e) {

        }
    }
}   

Step 4. On destroy

 XMPP.getInstance().removeChatListener(getActivity(), chatListener);
        if (chat != null && messageListener != null) {

            XMPP.getInstance().getConnection(acitiviy)).removeAsyncStanzaListener(stanzaListener);
            chat.removeMessageListener(messageListener);
        }

Hope this will help you and if you want more information take a look from here . Thankyou

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM