I am working in an android application to implement facebook chat and I have implemented it successfully using asmack libary. But when I tried to sent message when there is no internet connection XMPPException is not caught correctly. It shows Class file editor-source not found. I have downloaded my asmack libary from this link. Please look into my code and suggest me a solution.
Thanks.
public Boolean sentMessage(String message, Long senderid) {
ChatManager chatmanager = connection.getChatManager();
Chat newChat = chatmanager.createChat("-" + senderid
+ "#chat.facebook.com", new MessageListener() {
#Override
public void processMessage(Chat chat, Message message) {
System.out.println("Received message: " + message.getBody());
}
});
try {
newChat.sendMessage(message);
} catch (XMPPException e) {
return false;
}
return true;
}
Related
I use Quickblox for chat room
My code:
final QBChatDialog dialog = DialogUtils.buildPrivateDialog(id);
dialog.setType(QBDialogType.PRIVATE);
QBRestChatService.createChatDialog(dialog).performAsync(new QBEntityCallback<QBChatDialog>() {
#Override
public void onSuccess(QBChatDialog result, Bundle params) {
try {
QBChatMessage chatMessage = new QBChatMessage();
chatMessage.setBody("Hi there!");
dialog.sendMessage(chatMessage);
} catch (SmackException.NotConnectedException e) {
Log.i("errorCheck", "Chat: NO : " + e.getMessage());
}
}
#Override
public void onError(QBResponseException responseException) {
Log.i("errorCheck", "Chat: FAIL" + responseException.getMessage());
}
});
I get this error :
Client is not, or no longer, connected. error
But I'm sure my client is connected
You need to do the following before sending message:
qbChatDialog.initForChat(QBChatService.getInstance());
I am working with XMPP chatting application and i successfully integrated the chatting using XMPP, BUT now my requirement is to handle other type of message type='headline'
So when i receive this type of message then processMessage never called.
MMessageListener.class
private class MMessageListener implements ChatMessageListener {
public MMessageListener(Context contxt) {
}
#Override
public void processMessage(final org.jivesoftware.smack.chat.Chat chat,
final Message message) {
Log.i("MyXMPP_MESSAGE_LISTENER", "Xmpp message received: '"
+ message);
Log.e(TAG, "message type : " + message.getType());
}
}
ChatManagerListenerImpl.class
private class ChatManagerListenerImpl implements ChatManagerListener {
#Override
public void chatCreated(final org.jivesoftware.smack.chat.Chat chat,
final boolean createdLocally) {
if (!createdLocally)
chat.addMessageListener(mMessageListener);
}
}
I am stuck with this issue, please suggest
Thanks
In my Application, i want to get the chat history from the XMPP SMACK,For it i am sending the IQPacket stanza please check below
public void getChatHistory() throws Exception{
if (connection.isAuthenticated()){
ChatHistoryIq iq = new ChatHistoryIq("query");
iq.setType(IQ.Type.set);
iq.setStanzaId(loginUser);
System.out.println("************************************** Iq is : "+iq);
/*New code*/
connection.sendIqWithResponseCallback(iq, new PacketListener() {
#Override
public void processPacket(Stanza packet) throws NotConnectedException {
CharSequence mCharSequence = (CharSequence) packet.toXML();
System.out.println("((((((((((((((((( : " + mCharSequence);
String xml=String.valueOf(mCharSequence);
loadRSSFromURL(xml);
}
});
//The listener for receiving all the packets from the peer device
connection.addPacketListener(new PacketListener() {
#Override
public void processPacket(Stanza packet) throws NotConnectedException {
Log.i("Send IQ with Response", "****** message From : " + packet.getFrom());
Log.i("Send IQ with Response", "****** message To : " + packet.getTo());
Log.i("XML is *****************************: ", String.valueOf(packet.toXML()));
}
}, new PacketFilter() {
#Override
public boolean accept(Stanza packet) {
Log.e("$$$$$$$$$$$$$$$$$$$$$$$$ CHAT HISTORY Packet Filter From : ", packet.getFrom());
Log.e("$$$$$$$$$$$$$$$$$$$$$$$$ CHAT HISTORY Packet Filter To : ", packet.getTo());
Log.i("$$$$$$$$$$$$$$$$$$$$$$$$ CHAT HISTORY Packet Filter XML: ", packet.toString());
String xml=String.valueOf(packet.toXML());
loadRSSFromURL(xml);
return true;
}
});
connection.sendPacket(iq);
//
} else{
Toast.makeText(context,"User Not Authenticate",Toast.LENGTH_LONG).show();
}
}
I am getting the history from the above code but the problem is that , we are not able to handle the chat history , we are getting it only on our LOGCAT but not able to handle it.Means we want some callback methods to handle the chat history of XMPP. So please help to handle the chat history of XMPP..
Please check the screen shot of getting the XMPP response ScreenShot
When sending upstream message most of the times the message does not get to my server, and even when the message received to the server the onMessageSent(String msgId) function isn't called (the onMessageReceived(RemoteMessage fcmMessage) work very well).
Why the function isn't called and why do I need to send 10 upstream messages to get response from the firebase cloud messaging to my server?
new AsyncTask<Void, Void, String>() {
#Override
protected String doInBackground(Void... params) {
String sendTo = SENDER_ID + "#gcm.googleapis.com";
RemoteMessage.Builder data = new RemoteMessage.Builder(sendTo);
data.addData("Hello", "World");
try {
for (int i = 0; i < 10; i++) {
Thread.sleep(1000);
String messageID = getRandomString();
data.setMessageId(messageID);
Logger.d(TAG, "messageID: " + messageID);
FirebaseMessaging.getInstance().send(data.build());
}
} catch (Exception e) {
Logger.e(TAG, "Error sending upstream message: " + e.getMessage());
return "Error sending upstream message:" + e.getMessage();
}
return null;
}
#Override
protected void onPostExecute(String result) {
if (result != null) {
Logger.e(TAG, "send message failed: " + result);
}
}
}.execute(null, null, null);
}
Found out the problem!!!
The problem was on the server side.
Every time I send a message to the app (android), I started a new connection to the gcm server, when maintaining a continuous connection it worked great.
For the problem with the onMessageSent not called it was because, before you send the message you need to set time to live (setTtl(Time_in_seconds)) for the message.
RemoteMessage.Builder data = new RemoteMessage.Builder(mSendTo);
data.setMessageId(messageID);
data.setTtl(120);
data.addData("Hello", "World");
FirebaseMessaging.getInstance().send(data.build());
buttonUpstreamEcho.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Log.d(TAG, "Echo Upstream message logic");
String message = editTextEcho.getText().toString();
Log.d(TAG, "Message: " + message + ", recipient: " + token);
FirebaseMessaging.getInstance().send(new RemoteMessage.Builder(FCM_PROJECT_SENDER_ID + FCM_SERVER_CONNECTION)
.setMessageId(Integer.toString(RANDOM.nextInt()))
.addData("message", message)
.addData("action", BACKEND_ACTION_ECHO)
.build());
// To send a message to other device through the XMPP Server, you should add the
// receiverId and change the action name to BACKEND_ACTION_MESSAGE in the data
}
});
This is a sample Android project to showcase the Firebase Cloud Messaging (FCM) to manage upstream and downstream messages.
https://github.com/carlosCharz/FCMTest
This is the video in youtube that explains what it does.
https://www.youtube.com/watch?v=SEzOKSoAMG0
Hope you find it useful.
Using the builder pattern - it is always best to chain your calls to the setter methods. So my suggestion, and based on some working examples such as this one here, would be to change your code into something like this (note that I got rid of the for-loop - you can put it back if you need it, I don't see why - perhaps you were testing out?:
new AsyncTask<Void, Void, String>() {
#Override
protected String doInBackground(Void... params) {
String sendTo = SENDER_ID + "#gcm.googleapis.com";
String messageID = getRandomString();
try {
FirebaseMessaging.getInstance().send(new RemoteMessage.Builder(sendTo)
.setMessageId(messageID)
.addData("my_message", "Hello, World")
.build());
} catch (Exception e) {
Logger.e(TAG, "Error sending upstream message: " + e.getMessage());
return "Error sending upstream message:" + e.getMessage();
}
return null;
}
#Override
protected void onPostExecute(String result) {
if (result != null) {
Logger.e(TAG, "send message failed: " + result);
}
}
}.execute(null, null, null);
}
I hope this helps - try it out and let me know if it works or what errors you are getting.
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