目前,我正在编写以下代码以连接到openfire服务器,在所有活动中(或说片段):
XMPPTCPConnectionConfiguration config = XMPPTCPConnectionConfiguration.builder()
.setServiceName(HOST)
.setHost(HOST)
.setPort(PORT)
.setSecurityMode(ConnectionConfiguration.SecurityMode.disabled)
.setDebuggerEnabled(true).build();
conn = new XMPPTCPConnection(config);
conn.connect();
然后,我正在完成我的任务,如用户授权和身份验证(登录),获取名单等。
有没有其他方法可以创建一个全局连接,所以我不必每次都建立连接。
我希望实现类似,在每次应用程序启动之后,它应该只创建一次与Openfire服务器的连接,之后,我应该能够在任何Activity(或片段)上使用相同的连接。
答案 0 :(得分:1)
使用以下单身类:
public class XMPPConnectionManager {
String serviceName = "SERVICENAME";
String host = "HOST";
int port = 5222;
XMPPTCPConnectionConfiguration.Builder configBuilder;
AbstractXMPPConnection connection;
boolean setSecurityModeOn = false;
boolean shouldLogin = true;
private static XMPPConnectionManager instance = null;
private XMPPConnectionManager(){}
public static XMPPConnectionManager getInstance() {
if(instance == null) {
instance = new XMPPConnectionManager();
}
return instance;
}
public void connect(String username, String password){
XMPPTCPConnectionConfiguration.Builder configBuilder = XMPPTCPConnectionConfiguration.builder();
configBuilder.setUsernameAndPassword(username, password);
configBuilder.setServiceName(serviceName);
configBuilder.setHost(host);
configBuilder.setPort(port);
if(!setSecurityModeOn) {
configBuilder.setSecurityMode(ConnectionConfiguration.SecurityMode.disabled);
}
connection = new XMPPTCPConnection(configBuilder.build());
try {
connection.connect();
if(shouldLogin) {
connection.login();
}
} catch (SmackException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (XMPPException e) {
e.printStackTrace();
}
}
public void logUserIn(){
try {
connection.login();
} catch (XMPPException e) {
e.printStackTrace();
} catch (SmackException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
public void disconnect(){
if(connection != null) {
connection.disconnect();
}
}
public AbstractXMPPConnection getConnection() {
return connection;
}
public XMPPTCPConnectionConfiguration.Builder getConfigBuilder() {
return configBuilder;
}
public void setConfigBuilder(XMPPTCPConnectionConfiguration.Builder configBuilder) {
this.configBuilder = configBuilder;
}
public void setConnection(AbstractXMPPConnection connection) {
this.connection = connection;
}
public void setHost(String host) {
this.host = host;
}
public void setPort(int port) {
this.port = port;
}
public void setSetSecurityModeOn(boolean setSecurityModeOn) {
this.setSecurityModeOn = setSecurityModeOn;
}
public void setServiceName(String serviceName) {
this.serviceName = serviceName;
}
public void setShouldLogin(boolean shouldLogin) {
this.shouldLogin = shouldLogin;
}
}
使用:
XMPPConnectionManager.getInstance().connect("username","password");
要在任何其他类/活动中获取连接,只需再次获取管理器的单例类:
AbstractXMPPConnection connection = XMPPConnectionManager.getInstance().getConnection();
如果有任何问题,请告诉我。