學習過程中大家都碰到過連接被斷開的問題給困擾吧,下面教大家如何做到連接斷開後,重新連接
首先要創建連接監聽器,用來監聽連接狀態,這裡我寫了一個類
繼承了ConnectionListener,重寫了裡面5個方法,最重要的兩個方法connectionClosed()和connectionClosedOnError()
前者為連接正常斷開,後者是連接異常斷開,不管是正常還是異常,我們都要監聽到
這裡寫了一個定時器,兩秒進行連接一次,注釋寫的也很清楚,不做太多介紹
要注意的是我把用戶名和密碼都存到sharePreferences中了
[java]
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() {
}
}
其次就是給連接設置監聽器了,最好放在登錄方法裡,關閉連接方法裡移除監聽
[java]
// 添加連接監聽
TaxiConnectionListener connectionListener = new TaxiConnectionListener();
getConnection().addConnectionListener(connectionListener);
[java]
connection.removeConnectionListener(connectionListener);