Keep XMPP connection(using smack) alive throughout

2019-04-07 18:04发布

问题:

I am using the XMPP Connection(using smack) for chat in android application.I have made the connection with openfire and also i can send and receive the message.But the problem is that when i go in the XMPPClient.java activity then it made the connection.So i cant get any message till not go in that activity.So how can made the connection at the starting and then reuse at other activity.Code is in this 2 links ConnectionSettings file and the chatscreen in which we can do chat.In this link the comment line is also my questions so please also see that comment.

回答1:

Create global XMPPConnection object and Use below funciton and store in global XMPPConnection object and use that connection object everywhere. This is a sample gtalk example.

    public XMPPConnection login() throws XMPPException {

         ConnectionConfiguration config = new
         ConnectionConfiguration("talk.google.com",5222,"gmail.com");   
         config.setSecurityMode(SecurityMode.required);
         config.setTruststoreType("BKS");
         config.setTruststorePath("/system/etc/security/cacerts.bks");
         XMPPConnection connection = new XMPPConnection(config);        
        connection.connect();
        connection.login(username, password);
        Presence presence = new Presence(Presence.Type.available);
        presence.setMode(Presence.Mode.available);  
        connection.sendPacket(presence);
        try {
            Thread.sleep(3000);
        } catch (Exception ex) {
            ex.printStackTrace();
        }
     return connection;
} 


标签: android xmpp