一、简介
ConnectionListener 接口提供了对 connection 关闭相关事件的监听。
包括:
1、连接已经关闭 connectionClosed()
2、连接因为异常关闭 connectionClosedOnError()
3、在指定秒数后重新连接 reconnectingIn(int timeSecond)
4、重新连接成功 reconnectionSuccessful()
5、重新连接失败 reconnectionFailed()
所有实现了 ConnectionListener 接口并实现响应方法的类,
通过 connection.addConnectionListener(ConnectionListener connectionListener) 加入监听队列的监听器都会被调用。
二、使用方法
如果业务需要对连接的这些行为做处理,就可以按照下列步骤:
1、创建新的监听器:
ConnectionListener connListener = new ConnectionListener() {
public void connectionClosed() {
Log.d("SMACK", dateFormatter.format(new Date()) + " Connection closed (" + connection.hashCode() + ")");
}
public void connectionClosedOnError(Exception e) {
Log.d("SMACK", dateFormatter.format(new Date()) + " Connection closed due to an exception (" + connection.hashCode() + ")");
e.printStackTrace();
}
public void reconnectionFailed(Exception e) {
Log.d("SMACK", dateFormatter.format(new Date()) + " Reconnection failed due to an exception (" + connection.hashCode() + ")");
e.printStackTrace();
}
public void reconnectionSuccessful() {
Log.d("SMACK", dateFormatter.format(new Date()) + " Connection reconnected (" + connection.hashCode() + ")");
}
public void reconnectingIn(int seconds) {
Log.d("SMACK", dateFormatter.format(new Date()) + " Connection (" + connection.hashCode() + ") will reconnect in " + seconds);
}
};
- 2、添加到connection connection.addConnectionListener(connListener);
三、调用时机
1、packetReader.shutdown()
- for (ConnectionListener listener : connection.getConnectionListeners()) {
- try {
- listener.connectionClosed();
- } catch (Exception e) {
- e.printStackTrace();
- }
- }
2、connection.connect() 成功之后。
- if (connected && wasAuthenticated) {
- // Make the login
- ...
- notifyReconnection();
- }
http://blog.csdn.net/teamlet/article/details/25915731