Smack 中 ConnectionListener 的作用和使用

17 篇文章 0 订阅
15 篇文章 3 订阅

一、简介

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();
        }
 



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值