在整个应用程序中保持XMPP连接(使用smack)处于活动状态



我正在使用XMPP连接(使用smack)在Android应用程序中聊天。我已经与 openfire 建立了连接,我也可以发送和接收消息。但问题是,当我进入 XMPPClient.java 活动时,它建立了连接。所以我无法收到任何消息,直到不参加该活动。那么如何在开始时建立连接,然后在其他活动中重用。代码位于此 2 个链接的连接设置文件和我们可以进行聊天的聊天屏幕中。在此链接中,评论行也是我的问题,因此也请参阅该评论。

创建全局 XMPPConnection 对象 和 在下面使用功能并存储在全局 XMPPConnection 对象中,并在任何地方使用该连接对象。这是一个示例 gtalk 示例。

    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;
} 

最新更新