MQTT協議實現Android中的消息收發
- 2020 年 4 月 8 日
- 筆記
前言
MQTT
(Message Queuing Telemetry Transport,消息隊列遙測傳輸),基於發布/訂閱範式的消息協議,是一種極其簡單和輕量級的消息協議,專為受限設備和低頻寬、高延遲或不可靠的網路設計。今天主要說明一下MQTT
協議在Android中進行消息的收發應用,關於MQTT
協議的基礎內容請參考之前介紹的 MQTT
協議 相關內容。
效果
使用前先查看一下簡單的效果圖,MQTT
相關的連接、訂閱,發送及接收:
使用過程
- 依賴添加
implementation 'org.eclipse.paho:org.eclipse.paho.client.mqttv3:1.2.0' implementation 'org.eclipse.paho:org.eclipse.paho.android.service:1.1.1'
實際使用中發現,如果僅用第一條依賴也是能夠實現我們所需要的的消息收發功能的,其中MqttClient
類實現了MQTT
相關的連接、訂閱、發送及接收功能,第二條依賴是基於MqttClient
針對Android客戶端進行封裝了MqttAndroidClient
進行使用,其中實現了Android相關的廣播、服務相關內容。
使用中如果採用的是Androidx
開發環境,還需要添加如下依賴,否則MqttAndroidClient
服務中會找不到本地廣播服務,導致無法運行使用。
implementation 'androidx.legacy:legacy-support-v4:1.0.0'
- 許可權添加
<uses-permission android:name="android.permission.WAKE_LOCK" /> <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" /> <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" /> <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" /> <uses-permission android:name="android.permission.INTERNET" />
- 服務添加
<service android:name="org.eclipse.paho.android.service.MqttService"/>
這裡我們主要介紹
MqttClient
類實現的MQTT
協議消息的收發,而進一步封裝的MqttAndroidClient
和其使用過程基本類似,想要查看其具體使用,可跳轉對應Demo鏈接獲取詳細內容。
- 初始化
MQTT
客戶端內容,代理伺服器broker
選用的 HiveMQ公共代理 來實現:
public void initClient() { try { MemoryPersistence persistence = new MemoryPersistence(); // 設置唯一客戶端ID clientId = clientId + System.currentTimeMillis(); //設置訂閱方訂閱的Topic集合,遵循MQTT的訂閱規則,可以是多級Topic集合 final String topicFilter = topic; //服務品質,對應topicFilter final int qos = 0; //創建客戶端 sampleClient = new MqttClient(broker, clientId, persistence); //配置回調函數 sampleClient.setCallback(new MqttCallbackExtended() { @Override public void connectComplete(boolean reconnect, String serverUri) { setTextInfo("connectComplete: " + serverUri); try { //連接成功,需要上傳客戶端所有的訂閱關係 sampleClient.subscribe(topicFilter, qos); } catch (MqttException e) { setTextInfo("subscribeException: " + e.getMessage()); } } @Override public void connectionLost(Throwable cause) { setTextInfo("connectionLostException: " + cause.getMessage()); } @Override public void messageArrived(String topic, MqttMessage message) { setTextInfo("messageArrived:" + new String(message.getPayload())); } @Override public void deliveryComplete(IMqttDeliveryToken token) { setTextInfo("deliveryComplete"); } }); //創建連接選擇 MqttConnectOptions connOpts = createConnectOptions(userName, passWord); setTextInfo("Connecting to broker: " + broker); //創建服務連接 sampleClient.connect(connOpts); } catch (MqttException me) { setTextInfo("initException: " + me.getMessage()); } }
- 創建連接選擇如下,可設置用戶名、密碼:
private MqttConnectOptions createConnectOptions(String userName, String passWord) { MqttConnectOptions connOpts = new MqttConnectOptions(); connOpts.setCleanSession(true); connOpts.setUserName(userName); connOpts.setPassword(passWord.toCharArray()); connOpts.setAutomaticReconnect(true); // 設置連接超時時間, 單位為秒,默認30 connOpts.setConnectionTimeout(30); // 設置會話心跳時間,單位為秒,默認20 connOpts.setKeepAliveInterval(20); return connOpts; }
- 消息發布:
public void publishMsg() { String content = mEtMessage.getText().toString().trim(); if (TextUtils.isEmpty(content)) { content = "Hello MQTT "; } //此處消息體需要傳入byte數組 MqttMessage message = new MqttMessage(content.getBytes()); //設置品質級別 message.setQos(0); try { if (sampleClient != null && sampleClient.isConnected()) { /* * 消息發送到某個主題Topic,所有訂閱這個Topic的設備都能收到這個消息。 * 遵循MQTT的發布訂閱規範,Topic也可以是多級Topic。此處設置了發送到一級Topic。 */ sampleClient.publish(topic, message); setTextInfo("publishMsg: " + message); } } catch (MqttException e) { setTextInfo(" publishException: " + e.getMessage()); } }
- 連接斷開:
public void disconnect() { try { sampleClient.disconnect(); } catch (MqttException e) { setMqttMessage("disconnectException: " + e.getMessage()); } }
MQTT
協議實現Android中的消息收發就到這裡了,內容已上傳至Github開發記錄,歡迎點擊查閱及Star,我也會繼續補充其它有用的知識及例子在項目上。
歡迎點贊/評論,你們的贊同和鼓勵是我寫作的最大動力!
關注公眾號:幾圈年輪,查看更多有趣的技術、工具、閑言、資源。