我正在使用XMPP连接(使用smack)在android应用程序中进行聊天。我已经与openfire建立连接,我也可以发送和接收消息。但问题是当我进入XMPPClient.java活动时然后它就建立了连接。所以我不能得到任何消息,直到不进入那个活动。那么怎样才能在开始时建立连接,然后在其他活动中重用.Code在这2个链接ConnectionSettings file和{{ 3}}我们可以在其中聊天。在这个链接中,评论行也是我的问题所以请同时看看评论。
答案 0 :(得分:5)
创建全局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;
}