Androidpn里的Xmpp的理解

来源:互联网 发布:随便桌面软件下载 编辑:程序博客网 时间:2024/05/18 16:16

Androidpn里的Xmpp的理解

    博客分类:
  • Android
 

  XMPP(可扩展通讯和表示协议)是基于可扩展标记语言(XML)的协议,它用于即时消息(IM)以及在线探测。这个协议可能最终允许因特网用户向因特网上的其他任何人发送即时消息。用xmpp来实现android的push功能,感觉有点大材小用了,xmpp本身是一种即时通信协议。

  xmpp是一种用于即时通信的协议,使用过程有点类似于我们使用QQ的过程,其使用过程分为三步:

  1. 连接服务器,就好像打开QQ软件,看代码:

Java代码 复制代码 收藏代码
  1. if(!mXmppManager.isConnected()) {   
  2.     ConnectionConfiguration config = new ConnectionConfiguration(mHost, mPort);   
  3.     config.setSecurityMode(SecurityMode.required);   
  4.     config.setSASLAuthenticationEnabled(false);   
  5.     config.setCompressionEnabled(false);   
  6.        
  7.     XMPPConnection connection = new XMPPConnection(config);   
  8.     mXmppManager.setConnection(connection);   
  9.     try {   
  10.         connection.connect();   
  11.         Log.i(LOGTAG, "XMPP connected successfully");   
  12.         /**  
  13.          * 这个就是对于通信的xml文本进行解析的解析器,再把信息转换成IQ,这个相当于QQ的聊天信息 
  14.          * 如果要用这个协议,其IQ的子类和IQProvider要进行重写 
  15.          */  
  16.         ProviderManager.getInstance().addIQProvider("notification",   
  17.                 "androidpn:iq:notification",   
  18.                 new NotificationIQProvider());   
  19.            
  20.     } catch (XMPPException e) {   
  21.         Log.d(LOGTAG, "the connection is error ... ");   
  22.     }   
  23.     mXmppManager.runTask();   
  24. else {   
  25.     Log.i(LOGTAG, "XMPP connected already");   
  26.     mXmppManager.runTask();   
  27. }  

 

这一步主要是连接服务器,还有设置一些连接的参数,还有设置连接的解析器。

  2. 如果没有用户,注册新的帐号和密码

Java代码 复制代码 收藏代码
  1. if(!mXmppManager.isRegistered()){   
  2.     final String newUsername = newRandomUUID();   
  3.     final String newPassword = newRandomUUID();   
  4.     Registration registration = new Registration();   
  5.        
  6.     PacketFilter packetFilter = new AndFilter(new PacketIDFilter(   
  7.             registration.getPacketID()), new PacketTypeFilter(   
  8.             IQ.class));   
  9.     PacketListener packetListener = new PacketListener() {   
  10.         @Override  
  11.         public void processPacket(Packet packet) {   
  12.             // 服务器回复客户端  
  13.             if(packet instanceof IQ) {   
  14.                 IQ response = (IQ) packet;   
  15.                 if(response.getType() == IQ.Type.ERROR) { // 注册失败  
  16.                     if (!response.getError().toString().contains(   
  17.                             "409")) {   
  18.                         Log.e(LOGTAG,"Unknown error while registering XMPP account! " + response.getError().getCondition());   
  19.                     }   
  20.                 } else if(response.getType() == IQ.Type.RESULT) { // 注册成功  
  21.                     mXmppManager.setUsername(newUsername);   
  22.                     mXmppManager.setPassword(newPassword);   
  23.                     // 把用户名和密码都保存到磁盘  
  24.                     Editor editor = mSharedPrefs.edit();   
  25.                     editor.putString(Contants.XMPP_USERNAME, newUsername);   
  26.                     editor.putString(Contants.XMPP_PASSWORD, newPassword);   
  27.                     editor.commit();   
  28.                        
  29.                     mXmppManager.runTask();   
  30.                 }   
  31.             }   
  32.         }   
  33.     };   
  34.     // 给注册的Packet设置Listener,因为只有等到正真注册成功后,我们才可以交流  
  35.     mConnection.addPacketListener(packetListener, packetFilter);   
  36.        
  37.     registration.setType(IQ.Type.SET);   
  38.     registration.addAttribute("username", newUsername);   
  39.     registration.addAttribute("password", newPassword);   
  40.        
  41.     // 向服务器端,发送注册Packet包,注意其中Registration是Packet的子类  
  42.     mConnection.sendPacket(registration);   
  43.        
  44. else { // 已经注册过了  
  45.     mXmppManager.runTask();   
  46. }  

 

 只要连接了服务器了,客户端就可以向服务器端发送消息,发送是以Packet(数据包)来进行发送的,这个类有很多的子类,注册的子类为Registration。

 

 

 

 

 还有要注意的是,上面的addPacketListener方法不是给所有发送的数据包设置listener,而只是针对这次的注册Packet。

  3. 用注册的帐号和密码进行登陆(像用QQ号帐进行登陆一样)

Java代码 复制代码 收藏代码
  1. // 判断是否已经登陆过了,是否是在登陆状态  
  2. if(!mXmppManager.isAuthenticated()) {   
  3.     try {   
  4.         mConnection.login(mUsername, mPassword, "AndroidpnClient");   
  5.         // 设置XmppConnection的监听器  
  6.         if(mXmppManager.getConnectionListener() != null) {   
  7.             mConnection.addConnectionListener(mXmppManager.getConnectionListener());   
  8.         }   
  9.         // 设置服务器端推送的监听器  
  10.         PacketFilter packetFilter = new PacketTypeFilter(NotificationIQ.class);   
  11.         PacketListener packetListener = mXmppManager.getNotificationPacketListener();   
  12.         mConnection.addPacketListener(packetListener, packetFilter);   
  13.            
  14.         mXmppManager.runTask();   
  15.     } catch (XMPPException e) {   
  16.         // 登陆失败,应该重试   
  17.         String INVALID_CREDENTIALS_ERROR_CODE = "401";   
  18.         String errorMessage = e.getMessage();   
  19.         // 如果只是因为没有注册,则进行重新注册  
  20.         if (errorMessage != null && errorMessage.contains(INVALID_CREDENTIALS_ERROR_CODE)) {   
  21.             mXmppManager.reregisterAccount();    
  22.             return;   
  23.         }   
  24.         mXmppManager.startReconnectionThread();   
  25.     } catch (Exception e) { // 有可能mConnection都为空  
  26.         Log.e(LOGTAG, "LoginTask.run()... other error");   
  27.         Log.e(LOGTAG, "Failed to login to xmpp server. Caused by: " + e.getMessage());   
  28.         mXmppManager.startReconnectionThread(); // 启动重连线程  
  29.     }   
  30. else {   
  31.     mXmppManager.runTask();   
  32. }  

  

  这里设置了连接的监听器mConnection.addConnectionListener(),连接过程中有可以连接突然中断,连接出错等等问题,要进行监听。

  设置服务器推送信息的Listener,接收到信息后,显示给用户。
  如果出错的原因是401(无效的用户名和密码,则应该进行重新注册,再连接)

 

对于服务器push过来的信息进行处理,是在PacketListener类里面,这个接口里,只要实现一个方法processPacket(Packet packet),从传过来的Packet(数据包)里获取自己需要的数据:

Java代码 复制代码 收藏代码
  1. public void processPacket(Packet packet) {   
  2.     if(packet instanceof NotificationIQ) {   
  3.         NotificationIQ notification = (NotificationIQ) packet;   
  4.         if(notification.getChildElementXML().contains("androidpn:iq:notification")) {   
  5.             String notificationId = notification.getId();   
  6.             String notificationApiKey = notification.getApiKey();   
  7.             String notificationTitle = notification.getTitle();   
  8.             String notificationMessage = notification.getMessage();   
  9.             String notificationUri = notification.getUri();   
  10.   
  11.             Intent intent = new Intent(Contants.ACTION_SHOW_NOTIFICATION);   
  12.             intent.putExtra(Contants.NOTIFICATION_ID, notificationId);   
  13.             intent.putExtra(Contants.NOTIFICATION_API_KEY,notificationApiKey);   
  14.             intent.putExtra(Contants.NOTIFICATION_TITLE,notificationTitle);   
  15.             intent.putExtra(Contants.NOTIFICATION_MESSAGE, notificationMessage);   
  16.             intent.putExtra(Contants.NOTIFICATION_URI, notificationUri);   
  17.   
  18.             mXmppManager.getContext().sendBroadcast(intent);   
  19.         }   
  20.     }   
  21. }  

 

 

对于Androidpn项目的整体代码分析,看下一遍文章。

原创粉丝点击