Smack 中 ConnectionListener 的作用和使用

来源:互联网 发布:新店淘宝客推广 编辑:程序博客网 时间:2024/06/16 15:34




一、简介

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 plaincopy
  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 plaincopy
  1. if (connected && wasAuthenticated) {  
  2.            // Make the login  
  3.            ...  
  4.            notifyReconnection();  
  5.        }  

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



0 0
原创粉丝点击