学习过程中大家都碰到过连接被断开的问题给困扰吧,下面教大家如何做到连接断开后,重新连接
首先要创建连接监听器,用来监听连接状态,这里我写了一个类
继承了ConnectionListener,重写了里面5个方法,最重要的两个方法connectionClosed()和connectionClosedOnError()
前者为连接正常断开,后者是连接异常断开,不管是正常还是异常,我们都要监听到
这里写了一个定时器,两秒进行连接一次,注释写的也很清楚,不做太多介绍
要注意的是我把用户名和密码都存到sharePreferences中了
package com.techrare.listener;
import java.util.Timer;
import java.util.TimerTask;
import org.jivesoftware.smack.ConnectionListener;
import android.util.Log;
import com.techrare.taxicall.MainActivity;
import com.techrare.utils.Utils;
import com.techrare.utils.XmppConnection;
/**
* 连接监听类
*
* @author Administrator
*
*/
public class TaxiConnectionListener implements ConnectionListener {
private Timer tExit;
private String username;
private String password;
private int logintime = 2000;
@Override
public void connectionClosed() {
Log.i("TaxiConnectionListener", "連接關閉");
// 關閉連接
XmppConnection.getInstance().closeConnection();
// 重连服务器
tExit = new Timer();
tExit.schedule(new timetask(), logintime);
}
@Override
public void connectionClosedOnError(Exception e) {
Log.i("TaxiConnectionListener", "連接關閉異常");
// 判斷為帳號已被登錄
boolean error = e.getMessage().equals("stream:error (conflict)");
if (!error) {
// 關閉連接
XmppConnection.getInstance().closeConnection();
// 重连服务器
tExit = new Timer();
tExit.schedule(new timetask(), logintime);
}
}
class timetask extends TimerTask {
@Override
public void run() {
username = Utils.getInstance().getSharedPreferences("taxicall",
"account", MainActivity.context);
password = Utils.getInstance().getSharedPreferences("taxicall",
"password", MainActivity.context);
if (username != null && password != null) {
Log.i("TaxiConnectionListener", "嘗試登錄");
// 连接服务器
if (XmppConnection.getInstance().login(username, password)) {
Log.i("TaxiConnectionListener", "登錄成功");
} else {
Log.i("TaxiConnectionListener", "重新登錄");
tExit.schedule(new timetask(), logintime);
}
}
}
}
@Override
public void reconnectingIn(int arg0) {
}
@Override
public void reconnectionFailed(Exception arg0) {
}
@Override
public void reconnectionSuccessful() {
}
}
其次就是给连接设置监听器了,最好放在登录方法里,关闭连接方法里移除监听
// 添加連接監聽
TaxiConnectionListener connectionListener = new TaxiConnectionListener();
getConnection().addConnectionListener(connectionListener);
connection.removeConnectionListener(connectionListener);
https://blog.csdn.net/h7870181/article/details/12499955