Multiuser chat using smack not getting message listner - android

I am developing chat app using smack libary. I have issue in group chat. In my app i am creating group and in that members are auto joined.i want to notify all user when i send message in group even if they had not initiated chat.My code is as follow in that i have place listener in init method but unable to receive message.
//Initialize
public void init(String userId, String pwd, Context context) throws SmackException.NotConnectedException {
this.mUserName = userId;
this.mPassWord = pwd;
this.mContext = context;
sessionManager = new SessionManager(context);
if (userId.contains("#")) {
this.mUserName = userId.split("#")[0];
}
XMPPTCPConnectionConfiguration.Builder configBuilder = XMPPTCPConnectionConfiguration.builder();
configBuilder.setUsernameAndPassword(mUserName, mPassWord);
configBuilder.setSecurityMode(ConnectionConfiguration.SecurityMode.disabled);
configBuilder.setServiceName(XMPPCredential.SERVICE);
configBuilder.setHost(XMPPCredential.HOST);
configBuilder.setPort(XMPPCredential.PORT);
configBuilder.setResource("");
// configBuilder.setDebuggerEnabled(true);
mConnection = new XMPPTCPConnection(configBuilder.build());
PingManager pingManager = PingManager.getInstanceFor(mConnection);
pingManager.setPingInterval(300); // 2.5 min
pingManager.registerPingFailedListener(this);
mChatmanager.getInstanceFor(mConnection).addChatListener(this);
multiUserChatManager = MultiUserChatManager.getInstanceFor(mConnection);
mConnection.addAsyncStanzaListener(this, null);
mConnection.addSyncStanzaListener(this,null);
ReconnectionManager.getInstanceFor(mConnection).enableAutomaticReconnection();
mConnection.addConnectionListener(this);
// Connect with XMPP server
connectConnection(context);
}

Each MultiUserChat needs to add a Listener like this:
MultiUserChat muc = MultiUserChatManager.getInstanceFor(mConnection).getMultiUserChat( mucJid );
muc.addMessageListener(new MessageListener()...);

Related

Xmpp + openfire + server acknowledgement to the sender

I'm developing IM application.
I want to get acknowledgement at the time of
when message is received by the Openfire server
I have used below gradles
//XMPP Gradles
compile 'org.igniterealtime.smack:smack-android:4.1.0'
compile 'org.igniterealtime.smack:smack-tcp:4.1.0'
compile 'org.igniterealtime.smack:smack-im:4.1.0'
compile 'org.igniterealtime.smack:smack-extensions:4.1.0'
Note: I have already gone through each and every StackOverflow links and conclude that Openfire doesn't support XEP-0184, and it describes a mechanism for delivery receipts only.
I have also tried DeliveryReceiptManager and set their addReceiptReceivedListener but its not working.
Any workarounds or suggestions will be appreciated.
It is better to attach a common listener to every sent message and update your database(and hence your UI) accordingly.
Define a random UUID for each outgoing message:
String stanzaId = UUID.randomUUID().toString()
Attach the listener to your message:
xmppTcpConnection.addStanzaIdAcknowledgedListener(stanzaId , new StanzaListener()
{
#Override
public void processStanza(Stanza packet) throws SmackException.NotConnectedException, InterruptedException
{
// You can match your stanzaId here!
// packet.getStanzaId()
}
});
add:
compile "org.igniterealtime.smack:smack-tcp:4.2.0"
to get XMPPTCPConnection object.
Update: Try adding the listener before calling connect() on the xmppTcpConnection object.
while sending message attach DeliveryReceiptRequest.addTo(msg);
like this
Message msg = new Message(oppositeUserId, Message.Type.chat);
msg.setBody(mMessageBody);
msg.setStanzaId(messageId);
msg.setFrom(loginUserId);
DeliveryReceiptRequest.addTo(msg);
mXMPPTCPConnection.sendStanza(msg);
XmppDeliveryReceiptManager.java
public class XmppDeliveryReceiptManager implements ReceiptReceivedListener {
private static final String TAG = XmppDeliveryReceiptManager.class.getSimpleName();
Context mContext;
public XmppDeliveryReceiptManager(Context mContext) {
this.mContext = mContext;
Log.d(TAG, "XmppDeliveryReceiptManager : initialized ");
}
#Override
public void onReceiptReceived(String fromJid, String toJid, String receiptId, Stanza receipt) {
Log.d(TAG, "onReceiptReceived : receiptId = " + receiptId);
// do need full with "receiptId"
}
}
add this to your XMPP configuration
/* Add XMPP DeliveryReceiptManager */
ProviderManager.addExtensionProvider(DeliveryReceipt.ELEMENT,
DeliveryReceipt.NAMESPACE, new DeliveryReceipt.Provider());
ProviderManager.addExtensionProvider(DeliveryReceiptRequest.ELEMENT,
new DeliveryReceiptRequest().getNamespace(), new DeliveryReceiptRequest.Provider());
mXmppDeliveryReceiptManager = new XmppDeliveryReceiptManager(mContext);
mDeliveryReceiptManager = DeliveryReceiptManager.getInstanceFor(mXMPPTCPConnection);
mDeliveryReceiptManager.setAutoReceiptMode(DeliveryReceiptManager.AutoReceiptMode.always);
mDeliveryReceiptManager.addReceiptReceivedListener(mXmppDeliveryReceiptManager);

Dictionary as query string parameter in SignalR Android Client

C# Code
var querystringData = new Dictionary<string, string>();
querystringData.Add("UserName", LocalSettings.UserName);
querystringData.Add("LoginId", LocalSettings.LoginId);
hubConnection = new HubConnection("http://...", querystringData);
How do I pass the Dictionary as queryString in Android
Platform.loadPlatformComponent( new AndroidPlatformComponent() );
String host = "http://....;
String qs = "";
//Instead of String I want to pass List/Dictionary
HubConnection connection = new HubConnection(host, qs, true, new ConsoleLogger());
HubProxy hub = connection.createHubProxy("calculatorHub");
Referring http://whathecode.wordpress.com/2014/03/20/getting-started-with-the-java-signalr-sdk/ as the base
The C# client basically turns the dictionary you pass to "&{key}={value}" for each KeyValuePair. So you should be able to do the same on your side and pass to the HubConnection ctor as queryString.
Here my code, works perfect
String server = URL + "signalr";
String CONNECTION_QUERYSTRING ="Bearer=" + BaseActivity.getToken(activity).getAccess_token();
HubConnection connection = new HubConnection(server, CONNECTION_QUERYSTRING, false, new Logger() {
#Override
public void log(String message, LogLevel level) {
System.out.println(message);
}
});

Registration method in Asmack

i did not really like to take your time for my problem, but after 1 week of searching about registration code of Asmack, i ended up with try/fail on the clues,because there is extacly non simple of that on net, here is my code:
public class Registration extends IQ {
public static final String HOST = "http://127.0.0.1";
public static final int PORT = 9090;
public static final String SERVICE = "what is this?!";
public static final String USERNAME = "reza";
public static final String PASSWORD = "mypassword";
XMPPConnection connection;
public void create() {
ConnectionConfiguration connConfig =
new ConnectionConfiguration(HOST,PORT, SERVICE);
connection = new XMPPConnection(connConfig);
connection.connect();
AccountManager am = new AccountManager(connection);
Map<String, String> mp = new HashMap<String, String>();
// adding or set elements in Map by put method key and value
// pair
mp.put("username", USERNAME);
mp.put("password", PASSWORD);
// am.createAccount(mConfig.userName, mConfig.password);
am.createAccount(USERNAME, PASSWORD, mp);
}
#Override
public CharSequence getChildElementXML() {
// TODO Auto-generated method stub
return null;
}
}
but it returns error in codding can not instantiate the type XMPPConnection and the constructor AccountManager is not visible, can you help me with the code, and also i have questions what is service in the connection configuration and what is the CharSequence getChildElementXML() for? thanks alot, if you could lead me to an android smack definitive guide, that would best best thing some one did for me in past 20years , also this could be a guide for any one else who searching to learn like me ;)
If you are using openfire on server side then you can use userservice plugin there.
Using this plugin you can hit http or https web service to register the user or deactivate the user.

Get trouble with XMPPConnection

I try to get Room info related with login user with QuickBlox sdk. I edited chat sample app and try to grab room info according to this => http://www.igniterealtime.org/builds/smack/docs/latest/documentation/extensions/index.html
MultiUserChat.getRoomInfo, MultiUserChat.getJoinedRooms are not worked ! Connection is successful.NullPointer exception occur in Iterator<String> joinedRooms = MultiUserChat.getJoinedRooms(connection, "732374-5996#chat.quickblox.com");
public class MyChatController {
// ================= QuickBlox ===== Step 8 =================
// Get QuickBlox chat server domain.
// There will be created connection with chat server below.
public static final String CHAT_SERVER = QBChat.getChatServerDomain();
private XMPPConnection connection;
private ConnectionConfiguration config;
private Chat chat;
private String chatLogin;
private String password;
private String friendLogin;
private ChatManager chatManager;
public MyChatController(String chatLogin, String password) {
this.chatLogin = chatLogin;
this.password = password;
}
public void startChat(String buddyLogin) {
this.friendLogin = buddyLogin;
new Thread(new Runnable() {
#Override
public void run() {
// Chat action 1 -- create connection.
Connection.DEBUG_ENABLED = true;
config = new ConnectionConfiguration(CHAT_SERVER);
connection = new XMPPConnection(config);
try {
connection.connect();
connection.login(chatLogin, password);
// Chat action 2 -- create chat manager.
chatManager = connection.getChatManager();
// Chat action 3 -- create chat.
chat = chatManager.createChat(friendLogin, messageListener);
// Set listener for outcoming messages.
chatManager.addChatListener(chatManagerListener);
// Muc 2
if(connection != null){
// Get the rooms where user3#host.org has joined
Log.i("User Login =>", chatLogin);
Iterator<String> joinedRooms = MultiUserChat.getJoinedRooms(connection, "732374-5996#chat.quickblox.com");
/*while (joinedRooms.hasNext()) {
Log.i("Rooms =>", (String) joinedRooms.next());
}*/
}
} catch (XMPPException e) {
e.printStackTrace();
}
}
}).start();
}
Logcat =>
12-27 00:38:23.259: E/AndroidRuntime(15395): FATAL EXCEPTION: Thread-3743
12-27 00:38:23.259: E/AndroidRuntime(15395): java.lang.NullPointerException
12-27 00:38:23.259: E/AndroidRuntime(15395): at org.jivesoftware.smackx.muc.MultiUserChat.getRoomInfo(MultiUserChat.java:237)
12-27 00:38:23.259: E/AndroidRuntime(15395): at com.quickblox.sample.chat.MyChatController$3.run(MyChatController.java:95)
12-27 00:38:23.259: E/AndroidRuntime(15395): at java.lang.Thread.run(Thread.java:856)
New SDK and chat sample with several improvements have been released.
We almost finished working on our new sdk. We added new features for xmmp chat, increased stability. The sample will be released soon. You can try to use it for your project.

Not able to receive chat messages using smackx MultiUserChat API

I am trying to use smack API for Android to develop a chat room using gmail accounts. I managed to create a room and send messages to group. But when someone replies i am not able to receive incoming messages either directly on chat window or through program(muc.addMessageListener(myMessageListener) and PacketListener).
ConnectionConfiguration config = new ConnectionConfiguration("talk.google.com", 5222, "gmail.com");
config.setSASLAuthenticationEnabled(true);
connection = new XMPPConnection(config);
connection.connect();
connection.login("kandroid6990#gmail.com", "password");
muc = new MultiUserChat(connection, "private-chat-12325669-dead-beff-feed-fedcba987454#groupchat.google.com");
muc.sendConfigurationForm(new Form(Form.TYPE_SUBMIT));
muc.join("kandroid6990");
muc.invite("karthikbaskar3#gmail.com/User1", "Welcome!");
muc.invite("kamaraj6990#gmail.com/User2", "Welcome!");
Message msg = new Message("private-chat-12325669-dead-beff-feed-fedcba987454#groupchat.google.com", Message.Type.groupchat);
msg.addBody(Message.getDefaultLanguage(), messageText);
muc.sendMessage(msg);
Try
muc.addMessageListener(myMessageListener);
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
}
});
}
try this it may help in receive group chat message
Just implement group chat listener
PacketFilter filter = new MessageTypeFilter(Message.Type.groupchat);
XmppTool.con.addPacketListener(new PacketListener() {
#Override
public void processPacket(Packet packet) {
Message message = (Message) packet;
}
}
}
}, filter);

Categories

Resources