Enable custom XMPP message packet transceiver in Android

Source: Internet
Author: User

In the Android platform to implement XMPP im mainly using Asmack this package, Asmack is the implementation of the XMPP protocol. But Asmack can only help us to implement some basic message packet transceiver, if we need to implement a specific custom message packet transceiver needs our own processing.

I. Sending and receiving of ASMACK messages
    • Send message:

A message is sent with a message that can be sent using SendMessage (), which has two overloaded methods, one with a type of string and the other by the message object. A string of type string is the message to be sent; the party passing in the message object needs to write a class that inherits the message, overrides the toXML() method, and the return value of the method is the one toXML() to send. For example:

    ///1, send a message by passing in the SendMessage () method of the string type:Chatmanager Chatmanager = Xmppconnection.getchatmanager ();/** * String Userjid each other's Jid * MessageListener listener message Listener, when the message is received callback ProcessMessage (chat chat, message Message) method * /Chat mchat = Chatmanager.createchat (Mtouser, This); Mchat.sendmessage ("Your Content");///2. Send a message via the SendMessage () method of the incoming message object:    /** * Write a class that inherits the message override ToXml () method, the return value of the method is the messages to be sent */     Public  class mymessage extends Message {         @Override         PublicStringToXML() {return "Your Content"; }} Chatmanager Chatmanager = Xmppconnection.getchatmanager ();/** * String Userjid each other's Jid * MessageListener listener message Listener, when the message is received callback ProcessMessage (chat chat, message Message) method * /Chat mchat = Chatmanager.createchat (Mtouser, This); Mymessage Mymessage =NewMymessage (); Mchat.sendmessage (Mymessage);
    • Receive message messages:

Messages that receive the message type are mainly in the processMessage(Chat chat, Message message) method, and when the message is received, the method is invoked, the interface needs to be implemented MessageListener , and the methods in the interface are implemented processMessage(Chat chat, Message message) .

Second, send and receive the custom type of IQ knot message

When sending an IQ message containing a custom XML knot, the parsing provided by Asmack does not recognize these custom XML nodes, so we need to implement the parsing and assembling of the message packets ourselves.

1. Send an IQ message with a custom XML knot.

For example, send such an IQ message:

<iq id=‘123‘ type=‘get‘ from=‘[email protected]/B‘ to=‘[email protected]/s2‘><req var=‘read‘><attr var=‘temprature‘/></req></iq>

Send steps:

    //step:    ///1, write a class to inherit the IQ and override the Getchildelementxml () method, and the return value of the method will act as the body of the message.      Public  class myiq extends IQ {        @Override         PublicStringGetchildelementxml() {StringBuilder StringBuilder =NewStringBuilder (); Stringbuilder.append ("&lt;req var= ' read ' &gt;&lt; attr var= ' temprature '/&gt;&lt;/req&gt; ");returnStringbuilder.tostring (); }    }//2, send this IQ message packet with custom XML knotMyiq packet =NewMyiq (); Packet.settype (IQ. Type.get);//Set IQ junction typePacket.setfrom ("[Email protected]/b]);//Set IQ junction fromPacket.setto ("[Email protected]/s2]);//Set IQ knot toXmppconnection.sendpacket (packet);//Send Message Pack

2. The IQ message packet returned by the parsing server is included with the custom XML node in the message packet.

For example, an IQ message returned by the parsing server:

<iq  id  = ' " type  = ' result '  from  =  ' [Email protected]/s2 '  to  = ' [email protected]/b ' ;  Span class= "Hljs-tag" ><resp  xmlns  =,  <attr  Span class= "Hljs-attribute" >var  = ' temprature ' ; 17 </attr ;  </resp ;  </iq ;  

Resolution steps:

    //step:    ///1, write a class implements Packetlistener interface and implement the Processpacket (Packet Packet) method.      Public  class Mypacketlistener implements Packetlistener {        @Override         Public void Processpacket(Packet Packet) {//When a message packet is received, the method is recalled}    }//2, add Package listenerMypacketlistener Mmypacketlistener =NewMypacketlistener ();//The method has two parameters    ///First parameter: Packetlistener packet listener    ///second parameter: Packetfilter packet filterXmppconnection.addpacketlistener (Mmypacketlistener,NULL);//After completing these two steps, the Processpacket (Packet Packet) method in Mypacketlistener will be recalled when the message packet is received.     ///3, write a class to inherit the IQ and implement the Getchildelementxml () method.      Public  class getdataresp extends IQ {        ///For example, we want to get the Temprature and 172 properties in the IQ message pack above, declare these two values as member variables and generate the Get and set methods.          PublicString var; PublicString value; PublicStringGetVar() {returnvar;} Public void SetVar(String var) { This. var = var;} PublicStringGetValue() {returnValue;} Public void SetValue(String value) {his.value = value;}@Override         PublicStringGetchildelementxml(){//Assemble messageStringBuilder buf =NewStringBuilder (); Buf.append ("&lt;resp xmlns= ' get:data ' &gt;&lt;attr var= '");       ·            Buf.append (GetVar ()); Buf.append (">");            Buf.append (GetValue ()); Buf.append ("&lt;/attr&gt;&lt;/resp&gt;");returnBuf.tostring (); }    }///4, write a class implements Iqprovider and implement the PARSEIQ (Xmlpullparser parser) method in the interface.      Public  class getdatarespprovider implements iqprovider {        @Override         PublicIQParseiq(Xmlpullparser parser)throwsException {Getdataresp Getdataresp =NewGetdataresp ();//This object is the class object in the third step above            BooleanDone =false; while(!done) {intEventType = Parser.next ();if(EventType = = Xmlpullparser.start_tag) {if(Parser.getname (). Equals ("attr") {String var = parser.getattributevalue ("","var");//Get the value of the var attribute: tempratureString value = Parser.nexttext ();//Get the text of attr:Getdataresp.setvar (VAR);                    Getdataresp.setvalue (value); }                }Else if(EventType = = Xmlpullparser.end_tag) {if(Parser.getname (). Equals ("RESP") {done =true; }                }            }returnGETDATARESP; }    }///5, add iqprovider when configuring Connectionconfiguration    ///The first parameter is: the name of a String element    ///The second parameter is: String namespace    ///The third parameter is: object needs to pass in a Prvider objectProvidermanager.getinstance (). Addiqprovider ("RESP","Data",NewGetdatarespprovider ());//6, obtaining the corresponding message packet in the Processpacket (Packet Packet) method in the first step Mypacketlistener     Public  class Mypacketlistener implements Packetlistener {        @Override         Public void Processpacket(Packet Packet) {if(PacketinstanceofGETDATARESP) {Getdataresp Getdataresp = (GETDATARESP) packet;                String from = Getdataresp.getfrom ();                String to = Getdataresp.getto ();                String var = getdataresp.getvar ();            String value = Getdataresp.getvalue (); }        }    }
Iii. Summary
    • If a message type is sent with a custom XML knot, a class is written to inherit the message and override the toXML() method, and the return value of the method is the body of the message.
    • If you send a message with a custom XML knot in the IQ type, you need to write a class that inherits the IQ and overrides the getChildElementXML() method, and the return value of the method is used as the body of the message
    • The IQ message type returned by the server if it has a custom XML knot:
      • Write a class to inherit the IQ and override the getChildElementXML() method, make the information needed in the message returned by the server into a member variable, assemble the body of the message, and return it as the return value.
      • Write a class implements Iqprovider and implement the PARSEIQ (Xmlpullparser parser) method in the interface, then make the corresponding parsing process in the method, and finally return the IQ object in the previous step by returning the value.
      • The message body in the IQ message returned by the server must have a namespace.
      • This method is required to ProviderManager.getInstance().addIQProvider("resp", "data", new GetDataRespProvider()); add the corresponding iqprovider.
    • If you need to implement some custom parsing, you can modify the PacketParserUtils corresponding method in this class in the Asmack source code.
Here is the source address:

Click:

Enable custom XMPP message packet transceiver in Android

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.