First of all, the Internet of Things protocol mqtt protocol is based on the tcp/ip protocol and uses the official mqttclient framework.
/* *Initialize mqttclient */ private void init() { try { //MQTT connection settings options = new MqttConnectOptions(); //host is the host name, test is clientid, that is, the client ID connected to MQTT. It is generally represented by a client unique identifier. MemoryPersistence sets the save form of clientid, which is saved in memory by default client = new MqttClient(new Ip().host, username, new MemoryPersistence()); //Set whether to clear the session. If set to false here, it means that the server will retain the client's connection record. If set to true here, it means that every time you connect to the server, it will connect as a new identity. (false); //(myTopic,null,2,false); //Set the connection username (login_token); //Set the connection password (()); // Set the timeout unit to seconds (10); // Set the session heartbeat time unit to seconds The server will send a message to the client every 1.5*20 seconds to determine whether the client is online, but this method does not have a reconnect mechanism (60); //Set callback (new MqttCallback() { @Override public void connectionLost(Throwable cause) { //After the connection is lost, it is usually reconnected here. ("connectionLost----------"); } @Override public void deliveryComplete(IMqttDeliveryToken token) { //There will be executed here after publish ("deliveryComplete---------" + ()); } @Override public void messageArrived(String topicName, MqttMessage message) throws Exception { byte[] message1 = (); // The message obtained after subscribe will be executed here ("messageArrived----------" + message1[0] + (message1)); (message1[0] == 5); String id = new String(subBytes(message1, 1, 16), "UTF-8"); ("id received by mqtt" + id); DeviceList device = getBookById(id); ("device" + ()); String name = (); String gName = (); String type = (); ("Name as" + name + gName); /** * Use handler to send messages received by matt, in the format of binary data * */ Message msg = new Message(); = 1; if (message1[0] == 1) { // = name + "device heartbeat";// (msg); return; } if (message1[0] == 2) { = gName + "" + name + "Call the police"; msg.arg1 = (type); (msg); return; } if (message1[0] == 3) { = gName + "" + name + "Go online"; (msg); return; } if (message1[0] == 4) { = gName + "" + name + "Offline"; (msg); return; } if (message1[0] == 5) { if (message1[17] == 0) { = gName + "" + name + "close the door"; } else { = gName + "" + name + "Open the door"; } (msg); return; } if (message1[0] == 20 && message1[17] > 0 && message1[17] < 20) { = name + "Battery level: " + message1[17] + "%"; (msg); ("Battery:" + name + "Battery level: " + message1[17] + "%"); return; } if (message1[17] > 0) { SharedPreferences sp = getActivity().getSharedPreferences(id, getActivity().MODE_PRIVATE); // Get the editor for sp ed = (); // Save the username and password to sp as the display of key-value pairs ("battery", (message1[17])); // Submit username and password (); } } }); } catch (Exception e) { (); } } public byte[] subBytes(byte[] src, int begin, int count) { byte[] bs = new byte[count]; (src, begin, bs, 0, count); return bs; } //Get the Book object with attribute id according to id. public static DeviceList getBookById(String id) { DeviceList book = new DeviceList(); (id);//Set the incoming id value //() Compare whether the objects are equal according to id return ((book)); //Returns the Book object with the associated id. } private void connect() { new Thread(new Runnable() { @Override public void run() { try { (options); Message msg = new Message(); = 2; (msg); } catch (Exception e) { (); Message msg = new Message(); = 3; (msg); } } }).start(); } protected boolean onKeyDown(int keyCode, KeyEvent event) { if (client != null && keyCode == KeyEvent.KEYCODE_BACK) { try { (); } catch (Exception e) { (); } } return ().onKeyDown(keyCode, event); } @Override public void onDestroy() { (); try { (); (); } catch (MqttException e) { (); } } private void startReconnect() { scheduler = (); (new Runnable() { @Override public void run() { if (!()) { connect(); } } }, 0 * 1000, 10 * 1000, ); } Next usehandlermessageReceive message,And havenotifacationDisplayed in the notification bar page handler = new Handler() { @Override public void handleMessage(Message msg) { (msg); if ( == 1) { NotificationManager manager = (NotificationManager) getActivity().getSystemService(Context.NOTIFICATION_SERVICE); Notification myNotify = new Notification(); = ; = "New News"; = (); //Use the default sound |= Notification.DEFAULT_SOUND; //Use default vibration |= Notification.DEFAULT_VIBRATE; //Use default sound, vibration, flash = Notification.DEFAULT_ALL; // =Notification.FLAG_AUTO_CANCEL; // = Notification.FLAG_NO_CLEAR;// Cannot be automatically cleared RemoteViews rv = new RemoteViews(getActivity().getPackageName(), .activity_notification1); (.tv_desc, (String) ); = rv; Intent intent = new Intent(getActivity(), ); // (Intent.CATEGORY_LAUNCHER); // (Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS); contentIntent = (getActivity(), 0, intent, 0); = contentIntent; (i1++, myNotify); PowerManager pm = (PowerManager) getActivity().getSystemService(Context.POWER_SERVICE); wakeLock = (PowerManager.ACQUIRE_CAUSES_WAKEUP | PowerManager.SCREEN_DIM_WAKE_LOCK, "target"); boolean screen = (); if (!screen) {//If the screen is turned off (); (); } refresh(); } else if ( == 2) { ("Connected successfully"); ("Connection successful size" + ()); try { (myTopic, 1); (myTopic1, 1); } catch (MqttException e) { (); } } else if ( == 3) { //(, "The connection failed, the system is reconnecting", Toast.LENGTH_SHORT).show(); ("The connection failed, the system is reconnecting"); } } };
The above mqtt protocol example code for Android development is all the content I share with you. I hope you can give you a reference and I hope you can support me more.