Smack 中 ConnectionListener 的作用和使用




一、简介

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




incopy

  1. 2、添加到connection  connection.addConnectionListener(connListener); 



三、调用时机

1、packetReader.shutdown()

[java]  view plain copy
  1.    
  2. for (ConnectionListener listener : connection.getConnectionListeners()) {  
  3.                 try {  
  4.                     listener.connectionClosed();  
  5.                 } catch (Exception e) {  
  6.                     e.printStackTrace();  
  7.                 }  
  8.             }  
  9.    

2、connection.connect() 成功之后。

[java]  view plain copy
  1. if (connected && wasAuthenticated) {  
  2.            // Make the login  
  3.            ...  
  4.            notifyReconnection();  
  5.        }  

http://blog.csdn.net/teamlet/article/details/25915731



  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值