您的位置:首页 > 移动开发 > Android开发

即时通讯smack4.1.0-添加好友遇到的bug

2017-02-19 00:09 225 查看
先说一下问题:

org.jivesoftware.smack.SmackException$NotConnectedException: Client is not, or no longer, connected

这个错误从早上9点出现,搞了一下午加一晚上,最开始以为是代码问题,官网官方论坛试了无数代码(下面这块代码是报错的,google,stackoverflow,igniterealtime还有api示例代码,全都试了一遍,崩溃),依旧报这个错误。经过不断测试,原因找到了,但是完美的解决方法还没有找到。

public void search(String usernameStr){
//输入用户名
//搜索管理器
try {
UserSearchManager searchManager=new UserSearchManager(connection);
Log.e("UserSearchManager",connection.isConnected()+"");
String searchService="search." + connection.getServiceName();
Form searchForm=searchManager.getSearchForm(searchService);
//搜索的条件
Form answerForm=searchForm.createAnswerForm();
//根据用户名
answerForm.setAnswer("Username",true);
//指定搜索用户名关键字
answerForm.setAnswer("search",usernameStr.trim());
//获取查询结构
ReportedData  results=searchManager.getSearchResults(answerForm,searchService);
List<ReportedData.Row>rows=results.getRows();

List<String> list=new ArrayList<>();
for (ReportedData.Row row:rows){
String username=row.getValues("Username").get(0);
list.add(username);
}
ArrayAdapter<String> adapter=new ArrayAdapter<String>(this,R.layout.friend_search,R.id.tv_name,list);
lv_results.setAdapter(adapter);
} catch (SmackException.NoResponseException |XMPPException.XMPPErrorException|SmackException.NotConnectedException e) {
e.printStackTrace();

}
}


原因是我从登陆界面跳转添加好友界面之前,把登陆界面给finish掉了,我使用下面代码来建立连接,finish登陆界面之后把连接关闭了,导致在添加好友界面,一直报NotConnectedException。只要不finish登陆界面,就可以正常添加好友了,暂且先这样,更好的解决方法还没发现。发现网上使用SASL认证的连接没有出现这个问题,等基础功能做好后,再添加SASL认证登陆。

public class ConnectionManager {
private static XMPPTCPConnection connection;

//服务器名称
private static String serviceName="wen-vaio";
//服务器ip
private static String host="192.168.1.101";
//服务openfire端口号
private static int port=5222;

public static XMPPTCPConnection getConnection(){
if (connection==null) {
openConnection();
}
return connection;
}

/*打开连接*/
public static void openConnection(){
//设置连接配置
XMPPTCPConnectionConfiguration.Builder builder= XMPPTCPConnectionConfiguration.builder();
builder.setSecurityMode(ConnectionConfiguration.SecurityMode.disabled);
//builder.setCompressionEnabled(false);//连接套将使用流压缩。
builder.setDebuggerEnabled(true);
builder.setSendPresence(true);

builder.setHost(host);
builder.setPort(port);
builder.setServiceName(serviceName);
//取消安全认证
//spark源码LoginDialog.java
connection=new XMPPTCPConnection(builder.build());
try {
connection.connect();
Log.e("ConnectionManager",connection.isConnected()+"");

} catch (SmackException|IOException|XMPPException e) {
e.printStackTrace();
}
}

/*关闭连接*/
public static void release(){
if (connection!=null){
connection.disconnect();
}
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息