Understanding of XMPP in androidpn (Message pushing)

Source: Internet
Author: User

XMPP is a protocol based on the Extensible Markup Language (XML). It is used for instant messaging (IM) and online detection. This protocol may eventually allow Internet users to send instant messages to anyone else on the Internet. XMPP is used to implement the push function of Android. XMPP is a real-time communication protocol.

XMPP is a protocol used for instant communication. The process of using XMPP is similar to that of using QQ. The process is divided into three steps:

1. Connect to the server, as if to open the QQ Software and read the code:

If (! Mxmppmanager. isconnected () {connectionconfiguration Config = new connectionconfiguration (mhost, mport); config. setsecuritymode (securitymode. required); config. setsaslauthenticationenabled (false); config. setcompressionenabled (false); xmppconnection connection = new xmppconnection (config); mxmppmanager. setconnection (connection); try {connection. connect (); log. I (logtag, "XMPP connected successfully");/*** this is the parser that parses the XML text of the communication, and then converts the information to IQ, this is equivalent to QQ chat information * If this protocol is used, its IQ subclass and iqprovider must be rewritten */providermanager. getinstance (). addiqprovider ("notification", "androidpn: IQ: notification", new notifiqiqprovider ();} catch (xmppexception e) {log. D (logtag, "the connection is error... ");} mxmppmanager. runtask ();} else {log. I (logtag, "XMPP connected already"); mxmppmanager. runtask ();}

This step mainly involves connecting to the server, setting some connection parameters, and setting the connection parser.

2. If you do not have a user, register a new account and password.

If (! Mxmppmanager. isregistered () {final string newusername = newrandomuuid (); final string newpassword = newrandomuuid (); Registration = new registration (); packetfilter = new andfilter (New packetidfilter. getpacketid (), new packettypefilter (IQ. class); packetlistener = new packetlistener () {@ overridepublic void processpacket (packet) {// The server replies to the client If (packet instanceof IQ) {IQ response = (IQ) packet; If (response. GetType () = IQ. type. Error) {// If (! Response. geterror (). tostring (). Contains ("409") {log. E (logtag, "Unknown error while registering XMPP account! "+ Response. geterror (). getcondition () ;}} else if (response. getType () = IQ. type. result) {// mxmppmanager is successfully registered. setusername (newusername); mxmppmanager. setpassword (newpassword); // Save the username and password to the disk editor = msharedprefs. edit (); Editor. putstring (contants. xmpp_username, newusername); Editor. putstring (contants. xmpp_password, newpassword); Editor. commit (); mxmppmanager. runtask () ;}}}; // set listener for the registered packet, because mconnection can be communicated only when the registered packet is successfully registered. addpacketlistener (packetlistener, packetfilter); Registration. settype (IQ. type. set); Registration. addattristration ("username", newusername); Registration. addattribute ("password", newpassword); // send the register packet package to the server. Note that registry is a subclass of packet mconnection. sendpacket (registration);} else {// you have registered mxmppmanager. runtask ();}

As long as the server is connected, the client can send messages to the server, which is sent using packet (data packet). This class has many sub-classes, and the registered sub-classes are registration.

 

 

 

 

Note that the above addpacketlistener method does not set listener for all sent packets, but only registers packet for this time.

3. log in with the registered account and password (like logging in with the QQ account)

// Determine whether or not you have logged in and whether you are logged in. If (! Mxmppmanager. isauthenticated () {try {mconnection. login (musername, mpassword, "androidpnclient"); // set the xmppconnection listener if (mxmppmanager. getconnectionlistener ()! = NULL) {mconnection. addconnectionlistener (mxmppmanager. getconnectionlistener ();} // sets the listener packetfilter = new packettypefilter (icationicationiq. class); packetlistener = mxmppmanager. geticationicationpacketlistener (); mconnection. addpacketlistener (packetlistener, packetfilter); mxmppmanager. runtask ();} catch (xmppexception e) {// Login Failed. Retry string invalid_credentials_error _ Code = "401"; string errormessage = E. getmessage (); // re-register if (errormessage! = NULL & errormessage. contains (invalid_credentials_error_code) {mxmppmanager. reregisteraccount (); return;} mxmppmanager. startreconnectionthread ();} catch (exception e) {// it is possible that mconnection is empty log. E (logtag, "logintask. run ()... other error "); log. E (logtag, "failed to login to XMPP server. caused by: "+ E. getmessage (); mxmppmanager. startreconnectionthread (); // start the reconnection thread} else {mxmppmanager. runtask ();}

The connection listener mconnection. addconnectionlistener () is set here. During the connection process, problems such as sudden disconnection and connection error occur.

Set the listener of the server push information. After receiving the information, it is displayed to the user.
If the cause of the error is 401 (invalid username and password, you should re-register and connect again)

 

The information pushed by the server is processed in the packetlistener class. In this interface, you only need to implement the processpacket (packet) method and packet (packet) method) to obtain the required data:

public void processPacket(Packet packet) {    if(packet instanceof NotificationIQ) {    NotificationIQ notification = (NotificationIQ) packet;    if(notification.getChildElementXML().contains("androidpn:iq:notification")) {    String notificationId = notification.getId();            String notificationApiKey = notification.getApiKey();            String notificationTitle = notification.getTitle();            String notificationMessage = notification.getMessage();            String notificationUri = notification.getUri();            Intent intent = new Intent(Contants.ACTION_SHOW_NOTIFICATION);            intent.putExtra(Contants.NOTIFICATION_ID, notificationId);            intent.putExtra(Contants.NOTIFICATION_API_KEY,notificationApiKey);            intent.putExtra(Contants.NOTIFICATION_TITLE,notificationTitle);            intent.putExtra(Contants.NOTIFICATION_MESSAGE, notificationMessage);            intent.putExtra(Contants.NOTIFICATION_URI, notificationUri);            mXmppManager.getContext().sendBroadcast(intent);    }    }}

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.