android xmpp开发 asmack实现断线自动重连

http://blog.csdn.net/ming_light/article/category/1531703


asmack本身封装了断线重连机制,但是有一点需要注意

在设置链接属性钱,要加载ReconnectionManager这个类,否则没有效果。


直接上代码:

第一步

[java]  view plain copy
  1. try {  
  2.                     Class.forName("org.jivesoftware.smack.ReconnectionManager");  
  3.                 } catch (Exception e1) {  
  4.                 }    

第二步   设置链接参数,启动重连功能

[java]  view plain copy
  1. ConnectionConfiguration configuration = new ConnectionConfiguration(  
  2.                 Contents.HOST, Contents.PORT);  
  3.         configuration.setReconnectionAllowed(true);  

第三步   链接后注册监听

[java]  view plain copy
  1. connection.connect();  
  2. if (connection.isConnected()) {  
  3.                           
  4. connection.addConnectionListener(connectionListener);  
  5.                           
  6.                     }  
  7.   
  8.   
  9. public static ConnectionListener connectionListener = new ConnectionListener() {  
  10.   
  11.         @Override  
  12.         public void reconnectionSuccessful() {  
  13.             Log.i("connection""reconnectionSuccessful");  
  14.         }  
  15.   
  16.         @Override  
  17.         public void reconnectionFailed(Exception arg0) {  
  18.             Log.i("connection""reconnectionFailed");  
  19.         }  
  20.   
  21.         @Override  
  22.         public void reconnectingIn(int arg0) {  
  23.             Log.i("connection""reconnectingIn");  
  24.         }  
  25.   
  26.         @Override  
  27.         public void connectionClosedOnError(Exception arg0) {  
  28.             Log.i("connection""connectionClosedOnError");  
  29.               
  30.         } 

你可能感兴趣的:(Java,Android)