Initialize the SDK:
/** * Initialize SDK * * @param context context */public void INITSDK (context context) {String Clienti D = string.valueof (System.currenttimemillis () +userid); Mqttandroidclient = new Mqttandroidclient (Mcontext, Serveruri, clientId); Subscriptiontopics = new arraylist<> (); Mqttandroidclient.setcallback (New mqttcallbackextended () {@Override public void connectcomplete (boo Lean reconnect, String Serveruri) {if (reconnect) {LOG.D (TAG, "reconnected to:" + SE Rveruri); Because Clean Session was true, we need to re-subscribe//subscribetotopic (); PublishMessage (); } else {log.d (TAG, "Connected to:" + Serveruri); } connectsuccess = true; Subscribetotopic (); } @Override public void Connectionlost (Throwable cause) { Connectsuccess = false; LOG.E (TAG, "The Connection was lost." + cause.getlocalizedmessage ()); }//This DOES not work! @Override public void messagearrived (String topic, Mqttmessage message) throws Exception {LOG.D (TAG, "Incoming message:" +topic+ new String (Message.getpayload ())); } @Override public void Deliverycomplete (Imqttdeliverytoken token) {}}); }
Connecting remote services:
/** * Connect Remote service */public void ConnectServer () {mqttconnectoptions mqttconnectoptions = new mqttconnectopt Ions (); Mqttconnectoptions.setautomaticreconnect (TRUE); Mqttconnectoptions.setcleansession (FALSE); try {//addtohistory ("Connecting to" + Serveruri); Mqttandroidclient.connect (mqttconnectoptions, NULL, new Imqttactionlistener () {@Override PU Blic void onsuccess (Imqtttoken asyncactiontoken) {connectsuccess = true; Disconnectedbufferoptions disconnectedbufferoptions = new Disconnectedbufferoptions (); Disconnectedbufferoptions.setbufferenabled (TRUE); Disconnectedbufferoptions.setbuffersize (100); Disconnectedbufferoptions.setpersistbuffer (FALSE); Disconnectedbufferoptions.setdeleteoldestmessages (FALSE); Mqttandroidclient.setbufferopts (disconnectedbufferoptions); } @Override public void OnFailure (Imqtttoken asyncactiontoken, Throwable excepti ON) {LOG.E (TAG, "Failed-connect to:" + Serveruri); Exception.printstacktrace (); LOG.D (TAG, "onfailure:" + exception.getcause ()); Connectsuccess = false; } }); } catch (Mqttexception ex) {ex.printstacktrace (); } }
Get subscription information:
/** * Get subscription information
*/
Get subscription information if (!subscriptiontopics.contains (Gatewayid)) { subscriptiontopics.add (Gatewayid); } LOG.D (TAG, "Pre sub Topic:connect status=" + connectsuccess); LOG.D (TAG, "subtopic" + subscriptiontopics); Subscribetotopic (); }
To subscribe to an MQTT message:
/** * Subscribe to MQTT messages */private void Subscribetotopic () {try {if (subscriptiontopics.size () ==0) Return string[] topics = new string[subscriptiontopics.size ()]; Subscriptiontopics.toarray (topics); int[] Qoc = new Int[topics.length]; imqttmessagelistener[] mqttmessagelisteners = new Imqttmessagelistener[topics.length]; for (int i = 0; i < topics.length; i++) {Imqttmessagelistener Mqttmessagelistener = new Imqttmessagelis Tener () {@Override public void messagearrived (String topic, mqttmessage message) th Rows Exception {//message arrived! messages are processed after delivery log.d (TAG, topic + ":" + NE W String (Message.getpayload ())); Handlereceivedmessage (New String (Message.getpayload ()), topic); } }; Mqttmessagelisteners[i] = Mqttmessagelistener; LOG.D (TAG, "subscribetotopic:qoc=" + qoc[i]); } mqttandroidclient.subscribe (topics, QOC, NULL, new Imqttactionlistener () {@Override public void onsuccess (Imqtttoken imqtttoken) {log.d (TAG, "subscribed!"); } @Override public void OnFailure (Imqtttoken imqtttoken, Throwable throwable) { LOG.D (TAG, "Failed to subscribe"); }}, Mqttmessagelisteners); } catch (Mqttexception ex) {System.err.println ("Exception whilst subscribing"); Ex.printstacktrace (); } }
To process the received message:
private void Handlereceivedmessage (String message, String Gatewayid) {//Can send a broadcast notifier}
To send an MQTT message:
/** * Send MQTT message * * @param publishmessage the message to send * /private void PublishMessage (string PublishMessage, String publishtopic) { try { publishtopic = userId + "/" + Publishtopic; Mqttmessage message = new Mqttmessage (); Message.setpayload (Publishmessage.getbytes ()); Mqttandroidclient.publish (publishtopic, message); LOG.D (TAG, "Publishmessage:message Published \ n" + publishtopic + ":" + Message); if (!mqttandroidclient.isconnected ()) { log.d (TAG, Mqttandroidclient.getbufferedmessagecount () + "messages in Buffer. "); } } catch (Mqttexception e) { System.err.println ("Error Publishing:" + e.getmessage ()); E.printstacktrace (); } }
There are no encapsulated classes:
public class Subscribeclient {private final static String connection_string = "TCP://MQTT address: Mqtt Port"; Private Final Static Boolean Clean_start = true; Private final static short keep_alive = 30;//low-power network, but need to get data in time, heartbeat 30s private final static String client_id = "Client1"; Private final static string[] TOPICS = {//subscription information}; Private final static int[] Qos_values = {0, 0, 2, 0}; Private mqttclient mqttclient = null; Public subscribeclient (String i) {try {mqttclient = new mqttclient (connection_string); Simplecallbackhandler Simplecallbackhandler = new Simplecallbackhandler (); Mqttclient.registersimplehandler (Simplecallbackhandler);//Register to Receive Message method Mqttclient.connect (client_id + i, CLEAN_STAR T, keep_alive); Mqttclient.subscribe (TOPICS, qos_values);//Subscribe to the topic/** * After completing your subscription, you can increase your heartbeat, keep your network open, or post your own messages * /Mqttclient.publish (Publish_topics, "KeepAlive". GetBytes (), QOS_values[0], true); } catch (Mqttexception e) {//TODO auto-generated catch block E.printstacktrace (); }}/** * Simple callback function to handle the subject message received by the client * * @author Pig */class Simplecallbackhandler implements Mqtts Implecallback {/** * triggers when the client and broker are disconnected unexpectedly * you can re-subscribe this process * * @Override public Voi D Connectionlost () throws Exception {//TODO auto-generated Method Stub System.out.println ("Client and Bro Ker has been disconnected "); /** * After a client subscribes to a message, the method is responsible for callback receive processing message */@Override public void publisharrived (String topicna Me, byte[] payload, int Qos, Boolean retained) throws Exception {//TODO auto-generated method stub SYSTEM.OUT.PRINTLN ("Subscription topic:" + topicname); SYSTEM.OUT.PRINTLN ("message data:" + new String (payload)); SYSTEM.OUT.PRINTLN ("message Level (0,1,2):" + Qos); System.out.println ("is the message sent in real time (false= real-time, true= the last message left on the server):"+ retained); }}/** * Advanced callback * * @author Pig */class Advancedcallbackhandler implements Mqttsimplecallback { @Override public void Connectionlost () throws Exception {//TODO auto-generated method stub } @Override public void publisharrived (String arg0, byte[] arg1, int arg2, Boolean Arg3) throws Exception {//TODO auto-generated Method stub}}/** * @param args */public static void main (string[] args) {//TODO auto-generated method Stub new Subscribeclient ("" + i); }}
Android MQTT Message Push usage