Developing a Chat APP Group function using MucLight XEP with smack library
,the problem is I m able to send the message to group successfully but when its come to message listening I get confused,in smack library we have
multiUserChatLight.addMessageListener (new MessageListener ( ) {
#Override
public void processMessage(Message message) {
}
});
But its group Specific listener , means Its only listen to multiuserchatlight reference group, which some how not what I need,because every time whenever I reconnected with the chat server I need to register this listener against every group in which I involved , which is not good in opinion .
the other approach is to register packetlistener which is also little problematic with some cases like as member of group I received the message which I send into the group ,
So there is any alternative?
Can some one tell me where i am wrong ?
whenever you connected with server and authenticated you need to register always message listener. i have done using StanzaListener to add MucLight listener.
public RegisterXmppListener registerXmppListener;
public void registerMessageListener(){
debugLog("registerMessageListener");
if(mStanzaListener !=null)
connection.removeSyncStanzaListener(mStanzaListener);
StanzaTypeFilter filter = new StanzaTypeFilter(Message.class);
mStanzaListener=new StanzaListener() {
#Override
public void processStanza(Stanza stanza) throws SmackException.NotConnectedException, InterruptedException {
if(registerXmppListener!=null) {
registerXmppListener.onMessageReceived(stanza);
}
}
};
connection.addSyncStanzaListener(mStanzaListener, filter);
}
registerMessageListener register when you have authenticated with server.
Related
i'm using quickblox SDK in my project .
And i have a question about that.
Plz advise
I want to send push notification to other user in PUBLIC chat group.
I can do it with private chat by creating an event and sent to friend like this
public void createEvent(String message, List<Integer> userIds) {
StringifyArrayList<Integer> userIds_ = new StringifyArrayList<Integer>(userIds);
QBEvent event = new QBEvent();
event.setUserIds(userIds_);
event.setEnvironment(QBEnvironment.PRODUCTION);
event.setNotificationType(QBNotificationType.PUSH);
HashMap<String, Object> messageData = new HashMap<>();
messageData.put("message", message);
messageData.put("firID", KApp.getInstance().getCurrentUser().getId());
messageData.put("name", KApp.getInstance().getCurrentUser().getName());
event.setMessage(messageData);
QBPushNotifications.createEvent(event).performAsync(new QBEntityCallback<QBEvent>() {
#Override
public void onSuccess(QBEvent qbEvent, Bundle bundle) {
System.out.print("Create event success");
System.out.print(qbEvent.toString());
}
#Override
public void onError(QBResponseException e) {
System.out.print("Create event error : " + e.getLocalizedMessage());
}
});
}
But with PUBLIC chat dialog , i can't get list user id, it alway return empty.
How can i send push notification to other member in PUBLIC group ?
There is no sense in sending pushes to PUBLIC_GROUP because all users can chatting in public group chat. If you need notify occupants of dialog, use GROUP dialog. Note: in PUBLIC_GROUP you will also not receive pushes about messages when user is offline because PUBLIC_GROUP dialog not contain occupants_ids.
PUBLIC_GROUPS are open group. The difference between GROUP and PUBLIC_GROUP is that it does not keep associated participant's records like user_ids or unread_count . You have to store your participants data in your own backend server or else locally.
I am following the tutorial at: https://cloud.google.com/solutions/mobile/firebase-app-engine-android-studio
I have everything working and the email is sending every 2 minutes as it should. However, I now wish to extend this to trigger sending an email only upon data change on the Firebase node, not sending a message every 2 minutes.
To test I replaced the cron.xml file
from:
<?xml version="1.0" encoding="UTF-8"?>
<cronentries>
<cron>
<url>/hello</url>
<description>Send me an email of outstanding items in the morning</description>
<schedule>every 2 minutes</schedule>
</cron>
</cronentries>
to:
<?xml version="1.0" encoding="UTF-8"?>
<cronentries/>
To clear out the scheduled tasks.
But now upon making a change in the Firebase db, the email is never sent....
How can I keep my app engine server "listening" to the firebase node and subsequently produce an action given onDataChanged in real-time?
MyServlet class:
public class MyServlet extends HttpServlet {
static Logger Log = Logger.getLogger("com.example.username.myapplication.backend.MyServlet");
#Override
public void doGet(HttpServletRequest req, HttpServletResponse resp)
throws IOException {
Log.info("Got cron message, constructing email.");
//Create a new Firebase instance and subscribe on child events.
Firebase firebase = new Firebase("[firebase ref]");
firebase.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
// Build the email message contents using every field from Firebase.
final StringBuilder newItemMessage = new StringBuilder();
newItemMessage.append("This should arrive very closely after changing the data");
//Now Send the email
Properties props = new Properties();
Session session = Session.getDefaultInstance(props, null);
try {
Message msg = new MimeMessage(session);
//Make sure you substitute your project-id in the email From field
msg.setFrom(new InternetAddress("anything#[app-engine].appspotmail.com",
"Todo Nagger"));
msg.addRecipient(Message.RecipientType.TO,
new InternetAddress("myEmail#gmail.com", "Recipient"));
msg.setSubject("Feast Email Test");
msg.setText(newItemMessage.toString());
Transport.send(msg);
} catch (MessagingException | UnsupportedEncodingException e) {
Log.warning(e.getMessage());
}
}
public void onCancelled(FirebaseError firebaseError) {
}
});
}
}
Your question is actually a question about AppEngine and how to create a Servlet that starts automatically and automatically performs some initialization.
You will want to keep manual scaling on, but follow the steps here:
https://cloud.google.com/appengine/docs/java/config/appconfig#using_a_load-on-startup_servlet
for setting up your listeners on init() instead of an http request.
What you are trying is definitely possible and have seen it run elsewhere.
Simple answer is you can't do that yet.
Google cloud endpoints have a timeout of 1 min. Cron jobs also have a timeout.
What you need is triggers. This feature was demoed at Google io 16. Whenever data changes, a rest request is fired from firebase to a server and path of your choice.
Even I am waiting for this to arrive soon.
We have created a chat application using pubnub api on phonegap. We are using a common unique channel for two users (say A & B) to send and receive messages. Also, in addition to this, we have enabled pubnub gcm notification so that users can receive notifications when their app is either in the background or closed. Now when a user A sends a pubnub message to B and instantly changes the application or hides it, then the user A himself also receives a gcm notification oh his own message. This is the only issue that is troubling us. Rest all is working fine.
In your subscribe callback, can you detect if the application is not in the foreground, and if not in the foreground, return immediately?
This way, the logic which would deliver received messages to your application logic simply doesnt fire unless you are in foreground... ?
I ran into the same similar problem you did and so I rigged something together that works for me.
private boolean isFromSelf(final Object msgSent){
boolean isEcho = false;
String msgText = msgSent.toString();
JSONObject j;
String receiver = currentUserId; //a unique string ID for each user
try
{
j = new JSONObject(msgText);
String senderID = j.get("senderID").toString();
if (senderID.equals(receiver)){
isEcho = true;
}
}
catch(Exception e)
{
e.printStackTrace();
}
return isEcho;
}
It makes the assumption that every user that publishes a message to a channel will send their unique Id as "senderID" included in the payload. Then when a message is received, extract it from the payload and check it against the user's Id. So I add isFromSelf method as the first thing that is called when I receive a message, like this:
pN = new Pubnub(pub_key, sub_key);
try {
pN.subscribe(CHANNEL_NAME, new Callback() {
public void successCallback(String channel, Object msg) {
if (!isFromSelf(msg)) {
//Now add here what you want to do with the message
}
}
public void errorCallback(String channel, PubnubError error) {
Toast.makeText(MainActivity.this, "there was an error connecting", Toast.LENGTH_SHORT).show();
}
});
} catch (PubnubException e) {
e.printStackTrace();
}
So in your case, perhaps rig together a senderID check so that if you do receive a GCM from yourself, do not display notification at all, even if app is in background.
I am developing a chat application using Openfire and Asmack. I have a service running background to keep the connection alive and listen to incoming messages for all chats. So far, I've successfully implemented for one to one (single) chat. Code below is my listener for all single chat.
chatmanager = connection.getChatManager();
chatmanager.addChatListener(
new ChatManagerListener() {
#Override
public void chatCreated(Chat chat, boolean createdLocally)
{
if (!createdLocally) {
chat.addMessageListener(new MyNewMessageListener(getApplicationContext()));
}
}
});
But now my problem is how do i implement the same thing for MultiUserChat messages? Hope you guys could give me a helping hand over here. THANKS IN ADVANCE!
I solved my problem but not sure it is the best approach. However, hope this will help you guys and always welcome for better answer.
I first addInvitationListener and automatically join room once receive any invitation
MultiUserChat.addInvitationListener(connection, new InvitationListener() {
#Override
public void invitationReceived(Connection conn, String room, String inviter, String reason, String password, Message arg5) {
MultiUserChat muc = new MultiUserChat(connection, room);
try {
muc.join(connection.getUser().substring(0, connection.getUser().indexOf("#")));
} catch (XMPPException e) {
Log.d("Error","line 123 : "+e.toString());
}
muc.addMessageListener(new ServiceGroupMessageListener(getApplicationContext()));
}
});
Next, i store all the entered room name into Database. Then create a function that would grab the room name from database and finally add message listener to each of the room. So that when next time i open the app again, it will have message listener bind to each chat room.
***make sure change room setting to persistent at openfire side
https://github.com/fusesource/mqtt-client
i have an android application starting a background service where i have initiated an mqtt connection towards an apollo broker. when startService is called im initiating the MQTT from the onStartCommand setting hostname, port username, password etc.. followed by
connection = mqtt.callbackConnection();
the connect is successfull and i can clearly see that i have a consumer on my topic "uniqueId".
But when i send messages to my topic , the listener never calles the onPublish.. Another strange occurence is that if i loose my connection towards the broker , e.g i shut down the broker so that the active connection is broken, when the mqtt-client reconnects, it seems that it calles the listener and also the onPublish because then all the messages that i have stacked on my durable subscriber topic is delivered.. am i missing anything here regarding the listener?
isnt it suppose to actively consume the topic due to connection.subscribe??
Topic[] topics = { new Topic("uniqueId", QoS.AT_LEAST_ONCE) };
connection.subscribe(topics, new Callback<byte[]>() {
public void onSuccess(byte[] qoses) {
}
public void onFailure(Throwable value) {
value.printStackTrace();
}
});
connection.listener(new Listener() {
#Override
public void onConnected() {
}
#Override
public void onDisconnected() {
}
#Override
public void onFailure(Throwable value) {
}
#Override
public void onPublish(UTF8Buffer topic, Buffer payload, Runnable ack) {
ack.run();
}
});
I'm not familiar with Apollo, but I agree that the behaviour sounds incorrect. You could try testing against another broker to see if it works as expected, then file a bug against Apollo if necessary.
You could use e.g. test.mosquitto.org:1883 to test against, or use one of the other public ones listed on mqtt.org/software