i'm developing an android application using quickblox api. I'm using chat SMACK functionality (1 to 1 chat) and i try receive message from chat. I can retrieve the message text, but i can't get customs parameters.
Here is a screen about my message variable:
The values i need are values stored in 'map' : tempo, telefono, stato, nome , prefisso.. how i can retrieve that? I just try to search on quickblox documentation, but i have an api error when try to implement DefaultPacketExtension.
Thank you
Here is an example how to do it using QuickBlox Android SDK 1.1
To send message with additional parameters:
Map<String, Object> addinfoParams = new HashMap<String, Object>();
addinfoParams.put(Consts.AGE, 22);
addinfoParams.put(Consts.TYPE, "actor");
final String BODY = "Hey QuickBlox!";
Message message = createMsgWithAdditionalInfo(USER_ID, BODY, addinfoParams);
Log.i(TAG, "message: " + message.toXML());
try {
qbPrivateChat.sendMessage(USER_ID, message);
} catch (XMPPException e) {
e.printStackTrace();
}
...
private Message createMsgWithAdditionalInfo(int userId, String body, Map<?, ?> addinfoParams){
Message message = new Message(QBChatUtils.getChatLoginFull(userId), Message.Type.chat);
String addInfo = ToStringHelper.toString(addinfoParams, "", Consts.ESCAPED_AMPERSAND);
MessageExtension messageExtension = new MessageExtension(Consts.QB_INFO, "");
try {
messageExtension.setValue(Consts.ADDITIONAL_INFO, addInfo);
} catch (BaseServiceException e) {
e.printStackTrace();
}
message.addExtension(messageExtension);
message.setBody(body);
return message;
}
To receive message and get custom parameters:
chatMessageListener = new ChatMessageListener() {
#Override
public void processMessage(Message message) {
String from = message.getFrom();
String messageBody = message.getBody();
List<MessageExtension> messageExtensions = message.getExtensions();
}
#Override
public boolean accept(Message.Type type) {
switch (type) {
case normal:
case chat:
case groupchat:
return true;
default:
return false;
}
}
};
More info in Chat snippets https://github.com/QuickBlox/quickblox-android-sdk/blob/master/snippets/src/com/quickblox/snippets/modules/SnippetsChat.java
Related
There are two users A and B.
First is logged in and B is Offline.
A send message to B.
Now B is going to online but unable get message what A
has sent to B.
If A and B both logged in different devices at a time and
both are chatting then message sending and receiving is done
perfectly.
Help me how to get chat history for one to one chat ?
This is for send message :
public void sendTextMessage(View v) {
String message = msg_edittext.getEditableText().toString();
if (!message.equalsIgnoreCase("")) {
final ChatMessage chatMessage = new ChatMessage(user1, user2,
message, "" + random.nextInt(1000), false);
chatMessage.setMsgID();
chatMessage.body = message;
chatMessage.Date = CommonMethods.getCurrentDate();
chatMessage.Time = CommonMethods.getCurrentTime();
msg_edittext.setText("");
chatAdapter.add(chatMessage);
chatAdapter.notifyDataSetChanged();
//MainActivity activity = ((MainActivity) context);
getmService().xmpp.sendMessage(chatMessage);
}
}
public void sendMessage(ChatMessage chatMessage)
{
String body = gson.toJson(chatMessage);
if (!chat_created)
{
Mychat = ChatManager.getInstanceFor(connection).createChat(
chatMessage.receiver + "#"
+ "sspl163",
mMessageListener);
chat_created = true;
}
final Message message = new Message();
message.setBody(body);
message.setStanzaId(chatMessage.msgid);
message.setType(Message.Type.chat);
try {
if (connection.isAuthenticated())
Mychat.sendMessage(message);
else
login();
}
catch (NotConnectedException e) {
Log.e("xmpp.SendMessage()", "msg Not sent!-Not Connected!");
}
catch (Exception e) {}
}
This is for retrieving message :
private class MMessageListener implements ChatMessageListener
{
public MMessageListener(Context contxt) {}
#Override
public void processMessage(final org.jivesoftware.smack.chat.Chat chat, final Message message)
{
if (message.getType() == Message.Type.chat && message.getBody() != null)
{
final ChatMessage chatMessage = gson.fromJson(message.getBody(), ChatMessage.class);
processMessage(chatMessage);
}
}
private void processMessage(final ChatMessage chatMessage)
{
chatMessage.isMine = false;
SharedPreferences shared = context.getSharedPreferences("MyPREFERENCES", MODE_PRIVATE);
String user = (shared.getString("username", ""));
if(chatMessage.receiver.equalsIgnoreCase(user) && Chats.user2.equalsIgnoreCase(chatMessage.sender))
Chats.chatlist.add(chatMessage);
new Handler(Looper.getMainLooper()).post(new Runnable() {
#Override
public void run() {
Chats.chatAdapter.notifyDataSetChanged();
}
});
}
}
First Check your openfire settings from web admin
From
Server -> Server Settings -> Offline Messages and check Your settings
For me Following work.
I'm trying to send custom IQ from register device to ejabberd xmpp server for FCM configuration but still i can't received FCM notification and receiving Error like "user not registered at XMPP".
Step 1 : Created class for Custom IQ
public class IQGetSomething extends IQ {
public static final String ELEMENT = "push";
public static final String NAMESPACE = "p1:push";
String refreshedToken;
String userName;
public IQGetSomething(String refreshedToken,String userName) {
super(ELEMENT, NAMESPACE);
setType(Type.set);
this.refreshedToken = refreshedToken;
this.userName = userName;
}
#Override
protected IQChildElementXmlStringBuilder getIQChildElementBuilder(IQChildElementXmlStringBuilder xml) {
xml.rightAngleBracket();
xml.append("<keepalive max=\"120\"/>" +
"<session duration=\"60\"/>" +
"<body send=\"all\" groupchat=\"true\" from=" + "\"" + userName + "\"/>" +
"<status type=\"xa\">Text Message when in push mode</status>" +
"<offline>true</offline>" +
"<notification>"+
"<type>fcm</type>"+
"<id>" + refreshedToken + "</id>"+
"</notification>"+
"<appid>" + "com.appname"+ "</appid>");
return xml;
}
}
Step 2 : Send stanza to XMPP
#Override
public void authenticated(XMPPConnection connection, boolean resumed) {
SmackService.sConnectionState = ConnectionState.CONNECTED;
logI("Before n mostly after login $^&$^$...authenticated ");
logI("authenticated");
if (!mConnection.isSmEnabled()) {
mConnection.setUseStreamManagement(true);
mConnection.setUseStreamManagementResumption(true);
}
if (mConnection.isSmEnabled()) {
logI("stream M is enabled");
} else {
logI("stream M is not enabled");
}
final String refreshedToken = FirebaseInstanceId.getInstance().getToken();
IQGetSomething iqCustomPush = new IQGetSomething(refreshedToken, mUsername);
iqCustomPush.setStanzaId(refreshedToken);
Log.d("xml", iqCustomPush.toXML().toString());
try {
mConnection.sendStanza(iqCustomPush);
} catch (Exception e) {
e.printStackTrace();
}
}
Step 3 : Set Offline
public void setOffline() {
Presence presence = new Presence(Presence.Type.unavailable);
try {
mConnection.sendStanza(presence);
} catch (SmackException.NotConnectedException e) {
e.printStackTrace();
}
}
**LOGCAT
01-18 17:48:29.719 10219-10441/com.appname D/xml:
<iq id='refresh_token' type='set'><push xmlns='p1:push'><keepalive max="120"/><session duration="60"/><body send="all" groupchat="true" from="user_id"/><status type="xa">Text Message when in push mode</status><offline>true</offline><notification><type>fcm</type><id>refresh_token</id></notification><appid>com.appname</appid></push></iq>**
Note :- I changed here my refreshtoken with text "refresh_token" and package name with "com.appname". If anything i'm doing wrong than help me.
I am working on an instant messaging android application . I have successfully implemented the chat between my application and web application .I have used compile 'io.socket:socket.io-client:0.6.2' library to implement this. But when i installed the same app on another mobile phone, device to device communication did not work. I think i am missing something here. What i have to implement in my app now. Broadcast Receiver or GCM(Google Cloud Messaging). My code is as below:
1. ChatActivity.java
public class ChatActivity extends Activity {
public static final String TAG = ChatActivity.class.getSimpleName();
EditText edMessage;
Button sendMessage;
private Socket mSocket;
String sID, lID, md5StringRoomID, message, friendName, loggedInUser;
String frndID;
int smallerID, largerID;
AlmaChatDatabase almaChatDatabase;
// Chat messages list adapter
private MessagesListAdapter adapter;
private List<Message> listMessages;
private ListView listViewMessages;
boolean isSelf = false; // to check whether the message is owned by you or not.true means message is owned by you .
Message msg;
int loggedInUserID;
private String URL_FEED_Message = "";
APIConfiguration apiConfiguration;
{
try {
mSocket = IO.socket(Constants.CHAT_SERVER_URL);
Log.e("Socket", String.valueOf(mSocket));
} catch (URISyntaxException e) {
throw new RuntimeException(e);
}
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_chat);
sendMessage = (Button) findViewById(R.id.btnSendMessage);
almaChatDatabase = new AlmaChatDatabase(getApplicationContext());
loggedInUserID = almaChatDatabase.getUserID(); // Getting ID of the Logged in user from the database
Log.e("UserID", "Id of Logged in user " + loggedInUserID);
listMessages = new ArrayList<Message>();
adapter = new MessagesListAdapter(getApplicationContext(), listMessages);
listViewMessages = (ListView) findViewById(R.id.list_view_messages);
listViewMessages.setAdapter(adapter);
// Getting the ID of the friend from the previous screen using getExtras
Bundle bundle = getIntent().getExtras();
frndID = bundle.getString("ID");
Log.e("FriendID", frndID);
final int friendID = Integer.parseInt(frndID);
friendName = bundle.getString("name");
Log.e("FriendName", friendName);
loggedInUser = almaChatDatabase.getUserName(); // Name of logged in user
Log.e("LoggedInUser", loggedInUser);
// Converting first lowercase letter of every word in Uppercase
final String loggedInUpper = upperCase(loggedInUser);
//To find the current time
Date d = new Date();
final long time = d.getTime();
// Comparing the loggedInUserId and friendID
if (friendID < loggedInUserID) {
smallerID = friendID;
largerID = loggedInUserID;
} else {
smallerID = loggedInUserID;
largerID = friendID;
}
sID = String.valueOf(smallerID);
lID = String.valueOf(largerID);
String combinedID = sID + lID;
Log.e("combined ID", combinedID);
md5StringRoomID = convertPassMd5(combinedID); // Encrypting the combinedID to generate Room ID
Log.e("md5StringRoomID", md5StringRoomID);
// Using the API for loading old chat messages
apiConfiguration = new APIConfiguration();
String api_message = apiConfiguration.getApi_message(); // Getting the API of messages
URL_FEED_Message = api_message + md5StringRoomID; // md5String is the encrypted room ID here
Log.e("URL_FEED_MESSAGE", URL_FEED_Message);
Log.e("Network request", "Fresh Request");
// We first check for cached request
Cache cache = AppController.getInstance().getRequestQueue().getCache();
Cache.Entry entry = cache.get(URL_FEED_Message);
if (entry != null) {
// fetch the data from cache
try {
String data = new String(entry.data, "UTF-8");
try {
parseJsonFeed(new JSONArray(data));
} catch (JSONException e) {
e.printStackTrace();
}
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
} else {
JsonArrayRequest jsonArrayRequest = new JsonArrayRequest(URL_FEED_Message, new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray jsonArray) {
Log.e("JsonArray", String.valueOf(jsonArray));
if (jsonArray != null) {
parseJsonFeed(jsonArray);
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError volleyError) {
Log.e("ErrorResponse", String.valueOf(volleyError));
}
}
);
// Adding request to volley request queue
AppController.getInstance().addToRequestQueue(jsonArrayRequest);
}
edMessage = (EditText) findViewById(R.id.edtMessage);
//Listening on Events
mSocket.on(Socket.EVENT_CONNECT, onConnect);
mSocket.on(Socket.EVENT_CONNECT_ERROR, onConnectionError);
mSocket.on(Socket.EVENT_DISCONNECT, onDisconnect);
mSocket.on("send:notice", onReceive); // Listening event for receiving messages
mSocket.connect(); // Explicitly call connect method to establish connection here
mSocket.emit("subscribe", md5StringRoomID);
sendMessage.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//mSocket.emit("subscribe", md5String);
message = edMessage.getText().toString().trim();
Log.e("message", message);
if (!message.equals("")) {
edMessage.setText(" ");
JSONObject jsonObject = new JSONObject();
try {
jsonObject.put("room_id", md5StringRoomID);
jsonObject.put("user", loggedInUpper);
jsonObject.put("id", friendID);
jsonObject.put("message", message);
jsonObject.put("date", time);
jsonObject.put("status", "sent");
} catch (JSONException e) {
e.printStackTrace();
}
isSelf = true; // Boolean isSelf is set to be true as sender of the message is logged in user i.e. you
attemptToSend(loggedInUpper, message, isSelf);
mSocket.emit("send", jsonObject); // owner i.e LoggedIn user is sending the message
} else {
runOnUiThread(new Runnable() {
#Override
public void run() {
Toast.makeText(getApplicationContext(), "Please enter some text", Toast.LENGTH_LONG).show();
}
});
}
}
});
}
//Adding message in the arrayList
public void attemptToSend(String senderName, String message, boolean isSelf) {
msg = new Message(senderName, message, isSelf);
listMessages.add(msg);
adapter.notifyDataSetChanged();
playBeep();
}
// Playing sound when the message is sent by the owner
public void playBeep() {
try {
Uri notification = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
Ringtone r = RingtoneManager.getRingtone(getApplicationContext(), notification);
r.play();
} catch (Exception e) {
e.printStackTrace();
}
}
// encrypting string into MD5
public static String convertPassMd5(String pass) {
String password = null;
MessageDigest mdEnc;
try {
mdEnc = MessageDigest.getInstance("MD5");
mdEnc.update(pass.getBytes(), 0, pass.length());
pass = new BigInteger(1, mdEnc.digest()).toString(16);
while (pass.length() < 32) {
pass = "0" + pass;
}
password = pass;
} catch (NoSuchAlgorithmException e1) {
e1.printStackTrace();
}
return password;
}
// Converting first lowercase letter of every word in Uppercase
String upperCase(String source) {
StringBuffer res = new StringBuffer();
String[] strArr = source.split(" ");
for (String str : strArr) {
char[] stringArray = str.trim().toCharArray();
stringArray[0] = Character.toUpperCase(stringArray[0]);
str = new String(stringArray);
res.append(str).append(" ");
}
return res.toString().trim();
}
// Event Listeners
private Emitter.Listener onConnect = new Emitter.Listener() {
#Override
public void call(Object... args) {
Log.e("Socket", "Connected");
}
};
private Emitter.Listener onConnectionError = new Emitter.Listener() {
#Override
public void call(Object... args) {
Log.e("Error", "Error in connecting server");
}
};
private Emitter.Listener onDisconnect = new Emitter.Listener() {
#Override
public void call(Object... args) {
Log.e("Disconnect", "Socket Disconnected");
}
};
// Event Listener for receiving messages
private Emitter.Listener onReceive = new Emitter.Listener() {
#Override
public void call(final Object... args) {
Log.e("Receive", "Message received");
runOnUiThread(new Runnable() {
#Override
public void run() {
JSONObject data = (JSONObject) args[0];
Log.e("DATA", String.valueOf(data));
try {
JSONArray ops = data.getJSONArray("ops");
for (int i = 0; i < ops.length(); i++) {
JSONObject object = ops.getJSONObject(i);
String roomID = object.getString("room_id");
Log.e("RoomID", roomID); // Getting room ID from JSON array
Log.e("Md5RoomID", md5StringRoomID); // Getting room id which we have created using logged in user ID and room id of the user through which chat has to be done
//Comparing the room IDs
if (md5StringRoomID.equals(roomID)) {
String senderName = object.getString("user");
Log.e("Sender Name", senderName);
String senderID = object.getString("id");
Log.e("SenderID", senderID);
JSONObject message = object.getJSONObject("message");
String messageReceived = message.getString("text");
Log.e("Message Received", messageReceived);
String loggedInUSerNAme = almaChatDatabase.getUserName();
//If the message is sent by the owner to other from webapp ,then we need to check whether the sender is the loggedinUSer in the App or not and we will right align the messages .
if (loggedInUSerNAme.equalsIgnoreCase(senderName)) {
isSelf = true;
msg = new Message(senderName, messageReceived, isSelf);
listMessages.add(msg);
adapter.notifyDataSetChanged();
playBeep();
} else {
isSelf = false;
msg = new Message(senderName, messageReceived, isSelf);
listMessages.add(msg);
adapter.notifyDataSetChanged();
playBeep();
}
}
}
} catch (JSONException e) {
e.printStackTrace();
}
}
});
}
// Playing sound when the message is sent by other
public void playBeep() {
try {
Uri notification = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
Ringtone r = RingtoneManager.getRingtone(getApplicationContext(), notification);
r.play();
} catch (Exception e) {
e.printStackTrace();
}
}
};
// Parsing JSon Array which corresponds to the old chat messages
public void parseJsonFeed(JSONArray jsonArray) {
for (int i = 0; i < jsonArray.length(); i++) {
try {
JSONObject jsonObject = jsonArray.getJSONObject(i);
String roomID = jsonObject.getString("room_id");
Log.e("RoomID", roomID);
Log.e("Md5RoomID", md5StringRoomID);
// If Room ID(created using id of logged in user and id of friend) matches with the room id obtained from JSON String
if (md5StringRoomID.equals(roomID)) {
String userName = jsonObject.getString("user");
Log.e("Name", userName);
String loggedInUSerNAme = almaChatDatabase.getUserName();
Log.e("LoggedInUSer", loggedInUSerNAme);
//If the message is sent by the owner to other from webapp ,then we need to check whether the sender is the loggedinUSer in the App or not and we will right align the messages .
if (loggedInUSerNAme.equalsIgnoreCase(userName)) {
String message = jsonObject.getString("message");
Log.e("message", message);
isSelf = true;
msg = new Message(userName, message, isSelf);
listMessages.add(msg);
adapter.notifyDataSetChanged();
//playBeep();
} else {
JSONObject jsonMessage = jsonObject.getJSONObject("message");
String message = jsonMessage.getString("text");
isSelf = false;
msg = new Message(userName, message, isSelf);
listMessages.add(msg);
adapter.notifyDataSetChanged();
// playBeep();
}
}
} catch (JSONException e) {
e.printStackTrace();
}
// notify data changes to list adapter
//adapter.notifyDataSetChanged();
}
}
}
2.Constants.java
public class Constants {
public static final String CHAT_SERVER_URL = "http://192.168.2.250:3000/";
}
Everything is working her except device to device communication. I am able to send messages from my app to web app and also receiving messages from web App. But device to device communication is not working. Please help me to fix the issue.
I implemented a Group Chat mechanism in my Android where I have created groups and add members through REST API Plugin of Openfire. sending messages to to the same group not delivering messages to all members of the same group. Please see my Error Log for the same, and suggest me any solution regarding the same.
Log:
11-26 17:51:42.364 10035-10035/com.myoneapp.chat V/Cursor data==>>﹕ To User ID==> onCreateLoader=>terehokerahenge
11-26 17:51:47.018 10035-10654/com.myoneapp.chat I/System.out﹕ 05:51:47 PM SENT (0): <message to='terehokerahenge#conference.chat.spectratech.in' id='362-05' type='groupchat'><body>hi</body><SenderName></SenderName><mediaType>0</mediaType><request xmlns='urn:xmpp:receipts'/></message>
11-26 17:51:47.066 10035-10035/com.myoneapp.chat V/ChatWindow﹕ MESSAGE TYPE==>0
11-26 17:51:47.070 10035-10035/com.myoneapp.chat V/ChatWindow﹕ MESSAGE TYPE==>0
11-26 17:51:47.072 10035-10035/com.myoneapp.chat V/ChatWindow﹕ MESSAGE TYPE==>0
11-26 17:51:48.097 10035-10655/com.myoneapp.chat I/System.out﹕ 05:51:48 PM RECV (0): <message to="sanat#chat.spectratech.in/chat.spectratech.in" id="362-05" type="error" from="terehokerahenge#conference.chat.spectratech.in"><body>hi</body><SenderName/><mediaType>0</mediaType><request xmlns="urn:xmpp:receipts"/><error code="406" type="modify"><not-acceptable xmlns="urn:ietf:params:xml:ns:xmpp-stanzas"/></error></message>
11-26 17:51:48.102 10035-10654/com.myoneapp.chat I/System.out﹕ 05:51:48 PM SENT (0): <message to='terehokerahenge#conference.chat.spectratech.in' id='CGIln-9' type='error'><received xmlns='urn:xmpp:receipts' id='362-05'/></message>
Code:
new Thread(new Runnable() {
#Override
public void run() {
activity.getmService().xmpp.createMUCGroup(etGroupSubject.getText().toString(), mAppPreferences.getUserName());
getActivity().runOnUiThread(new Runnable() {
#Override
public void run() {
activity.getmService().xmpp.inViteUserstoGroup(jabberids);
}
});
}
}).start();
public void createMUCGroup(String gJID, String owner){
mMultiUserChat = getMUChatManager().getMultiUserChat(gJID + "#conference.chat.spectratech.in");
try {
mMultiUserChat.create(mAppPreferences.getUserName());
// Get the the room's configuration form
// org.jivesoftware.smackx.xdata.Form form = mMultiUserChat.getConfigurationForm();
// Create a new form to submit based on the original form
org.jivesoftware.smackx.xdata.Form form = mMultiUserChat.getConfigurationForm().createAnswerForm();
form.setAnswer("muc#roomconfig_publicroom", true);
form.setAnswer("muc#roomconfig_roomname", gJID);
form.setAnswer("muc#roomconfig_roomowners",gJID);
form.setAnswer("muc#roomconfig_persistentroom", true);
mMultiUserChat.sendConfigurationForm(form);
/*org.jivesoftware.smackx.xdata.Form submitForm = form.createAnswerForm();
// Add default answers to the form to submit
for (java.util.Iterator fields = (java.util.Iterator) form.getFields(); fields.hasNext(); ) {
org.jivesoftware.smackx.xdata.FormField field = (org.jivesoftware.smackx.xdata.FormField) fields.next();
if (!org.jivesoftware.smackx.xdata.FormField.Type.hidden.equals(field.getType()) && field.getVariable() != null) {
// Sets the default value as the answer
submitForm.setDefaultAnswer(field.getVariable());
}
}*/
// Sets the new owner of the room
/*java.util.List owners = new java.util.ArrayList();
owners.add(mAppPreferences.getUserName()+"#chat.spectratech.in");
submitForm.setAnswer("muc#roomconfig_roomowners", owners);
// Send the completed form (with default values) to the server to configure the room
mMultiUserChat.sendConfigurationForm(submitForm);*/
}catch (Exception e){
e.printStackTrace();
}
}
public void inViteUserstoGroup(java.util.ArrayList<String> users){
getMUChatManager().addInvitationListener(MyXMPP.this);
for (int i = 0; i < users.size(); i++) {
try {
mMultiUserChat.invite(users.get(i)+"#chat.spectratech.in", "Meet me in this group.");
} catch (org.jivesoftware.smack.SmackException.NotConnectedException e) {
e.printStackTrace();
}
}
}
#Override
public void invitationReceived(org.jivesoftware.smack.XMPPConnection xmppConnection, org.jivesoftware.smackx.muc.MultiUserChat multiUserChat, String s, String s1, String s2, org.jivesoftware.smack.packet.Message message) {
try {
System.out.println("Invitation Received==========================>");
mMultiUserChat.join(s1);
} catch (org.jivesoftware.smack.SmackException.NoResponseException e) {
e.printStackTrace();
} catch (org.jivesoftware.smack.XMPPException.XMPPErrorException e) {
e.printStackTrace();
} catch (org.jivesoftware.smack.SmackException.NotConnectedException e) {
e.printStackTrace();
}
}
It returning Error 406, Not acceptable
I think you are missing the implementation of auto accepting Group chat joining Request in your code.
Below code is working for AMACK group chat using Openfire Server
1. Creating XMPP Connection
XMPPTCPConnection connection = new XMPPTCPConnection(config);
connection.connect();
connection.login(ID1, password1);
Presence presence = new Presence(Presence.Type.available);
connection.sendPacket(presence);
2. Creating Persistant Group Chat Room
MultiUserChat chatRoom = new MultiUserChat(connection, "room786#conference.dishaserver");
chatRoom.create("nagarjuna");
Form form = chatRoom.getConfigurationForm().createAnswerForm();
form.setAnswer("muc#roomconfig_publicroom", true);
form.setAnswer("muc#roomconfig_roomname", "room786");
form.setAnswer("muc#roomconfig_roomowners",owners);
form.setAnswer("muc#roomconfig_persistentroom", true);
chatRoom.sendConfigurationForm(form);
3. Sending invitation to ride participants
MultiUserChat.addInvitationListener(connection, groupChatListener);
chatRoom.invite("surya#dishaserver", "hi surya");
4. Auto accepting the request of RIDER to join group chat
public class GroupChatListener implements InvitationListener{
String nickname;
public GroupChatListener(String nick)
{
nickname = nick;
}
#Override
public void invitationReceived(XMPPConnection con, String room,String inviter, String reason, String password, Message message)
{
System.out.println(" Entered invitation handler... ");
try
{
MultiUserChat chatRoom = new MultiUserChat(con, room);
chatRoom.join(nickname);
}
catch (NoResponseException | XMPPErrorException| NotConnectedException e)
{
e.printStackTrace();
} catch (SmackException e)
{
e.printStackTrace();
}
System.out.println(" Invitation Accepted... ");
}
}
5. Sending message to group chat members
private static void sendMessageToRoomOccupants(XMPPTCPConnection connection) throws NotConnectedException
{
Message msg = new Message("room789#conference.dishaserver",Message.Type.groupchat);
msg.setBody("This is nagarjuna friednds. Please join this room and let us have fun."); connection.sendPacket(msg);
}
6. Receiving the group chat message by ride users
MultiUserChat chatRoom = new MultiUserChat(connection, "room789#conference.dishaserver");
chatRoom.addMessageListener(new GroupChatMsgListener());
package com.disha.test;
import org.jivesoftware.smack.PacketListener;
import org.jivesoftware.smack.SmackException.NotConnectedException;
import org.jivesoftware.smack.packet.Packet;
public class GroupChatMsgListener implements PacketListener
{
#Override
public void processPacket(Packet packet) throws NotConnectedException
{
System.out.println(" Received group cht messages... ");
System.out.println("from : "+packet.getFrom());
System.out.println("to : "+packet.getTo());
System.out.println(packet.toString());
}
}
In order to send messages in the groupchat you need to join it first:
mMultiUserChat.join("yournickname");
Its not working in 4.1.9 version, you can try this one:
public MultiUserChat mMultiUserChat;
private MultiUserChatManager mMultiUserChatManager;
mMultiUserChatManager = MultiUserChatManager.getInstanceFor(mAbstractXMPPConnection);
mMultiUserChatManager.addInvitationListener(this);
mMultiUserChat = mMultiUserChatManager.getMultiUserChat(room);
mMultiUserChat.addMessageListener(this);
try {
mMultiUserChat.join(yournickname);
// mMultiUserChat.sendConfigurationForm(new Form(DataForm.Type.submit));
} catch (SmackException.NoResponseException e) {
e.printStackTrace();
} catch (XMPPException.XMPPErrorException e) {
e.printStackTrace();
} catch (SmackException.NotConnectedException e) {
e.printStackTrace();
}
and for send message:
Message msg = new Message(room, Message.Type.groupchat);
msg.setBody(message);
mMultiUserChat.sendMessage(msg);
Hope this is helpful, thanks.
I send notification one client to another successfully. With this method:
ParsePush push = new ParsePush();
String yourMessage = "hello world";
push.setChannel("seconddevice");
push.setMessage(yourMessage);
push.sendInBackground();
my application:
public class ParseApplication extends Application {
String YOUR_APPLICATION_ID="xxx",YOUR_CLIENT_KEY="yyy";
#Override
public void onCreate() {
super.onCreate();
// Add your initialization code here
Parse.initialize(this, YOUR_APPLICATION_ID, YOUR_CLIENT_KEY);
ParseUser.enableAutomaticUser();
ParseACL defaultACL = new ParseACL();
// If you would like all objects to be private by default, remove this line.
defaultACL.setPublicReadAccess(true);
ParseACL.setDefaultACL(defaultACL, true);
PushService.subscribe(this, DEVICE_NAME, NotificationBck.class);
}
}
It works. But when I receive message in second device can I have which device send this notification?
From the Parse Android docs:
The Intent object which is passed to the receiver contains an extras Bundle with two useful mappings. The com.parse.Channel key points to a string representing the channel that the message was sent on. The com.parse.Data key points to a string representing the JSON-encoded value of the "data" dictionary that was set in the push notification.
So, in your receiver, you'd be able to check the data (assuming you've set it when pushing):
#Override
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
String channel = intent.getExtras().getString("com.parse.Channel");
String encodedJson = intent.getExtras().getString("com.parse.Data");
Log.d(TAG, "got action " + action + " on channel " + channel + " with:");
JSONObject json = decodeJsonObjectFrom(encodedJson);
logContentsOf(json);
}
private JSONObject decodeJsonObjectFrom(String encodedJson) {
try {
return new JSONObject(encodedJson);
} catch (JSONException e) {
return new JSONObject();
}
}
private void logContentsOf(JSONObject json) {
while (json.keys().hasNext()) {
String key = (String) json.keys().next();
Log.d(TAG, "..." + key + " => " + getStringFrom(json, key));
}
}
private String getStringFrom(JSONObject json, String key) {
try {
return (String) json.get(key);
} catch (JSONException e) {
return "";
}
}