在Android开发中,与远程服务器进行通信是一个常见的需求。MQTT(Message Queuing Telemetry Transport)是一种轻量级的、基于发布/订阅模式的消息传输协议,广泛应用于物联网(IoT)场景中。在阿里云物联网平台中,物联网设备与APP之间的交互是通过云产品消息转发实现,所以需要讲APP通过mqtt方式接入平台。本文将介绍Android Studio中开MQTT调试助手,以接入阿里云平台为例。
一、构建MqttService工具类
1. 添加依赖
在app/build.gradle文件中添加Eclipse Paho MQTT Android Client的依赖:
dependencies { implementation ("org.eclipse.paho:org.eclipse.paho.client.mqttv3:1.2.5")implementation ("org.eclipse.paho:org.eclipse.paho.android.service:1.1.1")
}
2. 打开对应权限
在AndroidManifest.xml中添加了必要的网络权限。
<uses-permission android:name="android.permission.INTERNET"/>
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>
3. 创建MqttService类
import android.content.Context;
import android.content.Intent;
import android.util.Log;import org.eclipse.paho.client.mqttv3.IMqttClient;
import org.eclipse.paho.client.mqttv3.IMqttDeliveryToken;
import org.eclipse.paho.client.mqttv3.MqttCallback;
import org.eclipse.paho.client.mqttv3.MqttClient;
import org.eclipse.paho.client.mqttv3.MqttConnectOptions;
import org.eclipse.paho.client.mqttv3.MqttException;
import org.eclipse.paho.client.mqttv3.MqttMessage;
import org.eclipse.paho.client.mqttv3.persist.MemoryPersistence;public class MqttService {private Context context;private static final String TAG = "MqttService";private IMqttClient client;private String brokerUrl;private String clientId;private String username;private String password;public MqttService(Context context, String brokerUrl, String clientId, String username, String password) {this.context = context;this.brokerUrl = brokerUrl;this.clientId = clientId;this.username = username;this.password = password;}/*** 连接*/public void connect() {try {client = new MqttClient(brokerUrl, clientId, new MemoryPersistence());MqttConnectOptions options = new MqttConnectOptions();options.setUserName(username);options.setPassword(password.toCharArray());options.setCleanSession(true);client.setCallback(new MqttCallback() {@Overridepublic void connectionLost(Throwable cause) {Log.e(TAG, "Connection lost: " + cause.getMessage());}@Overridepublic void messageArrived(String topic, MqttMessage message) throws Exception {Intent MSGintent = new Intent();MSGintent.setAction("com.example.aliyuniot.MainActivity");MSGintent.putExtra("message", new String(message.getPayload()));//接收的数据context.sendBroadcast(MSGintent);//广播接受到的数据Log.d(TAG, "Message arrived. Topic: " + topic + " Message: " + new String(message.getPayload()));}@Overridepublic void deliveryComplete(IMqttDeliveryToken token) {Log.d(TAG, "Delivery complete.");}});client.connect(options);Log.d(TAG, "Connected to broker: " + brokerUrl);} catch (MqttException e) {e.printStackTrace();Log.e(TAG, "Failed to connect to broker: " + e.getMessage());}}/*** 订阅消息* @param topic 订阅主题*/public void subscribe(String topic) {try {client.subscribe(topic);Log.d(TAG, "Subscribed to topic: " + topic);} catch (MqttException e) {e.printStackTrace();Log.e(TAG, "Failed to subscribe to topic: " + e.getMessage());}}/*** 发布信息* @param topic 主题* @param payload 发布内容*/public void publish(String topic, String payload) {try {MqttMessage message = new MqttMessage(payload.getBytes());client.publish(topic, message);Log.d(TAG, "Published message to topic: " + topic + " Message: " + payload);} catch (MqttException e) {e.printStackTrace();Log.e(TAG, "Failed to publish message: " + e.getMessage());}}/*** 断开连接*/public void disconnect() {try {client.disconnect();Log.d(TAG, "Disconnected from broker: " + brokerUrl);} catch (MqttException e) {e.printStackTrace();Log.e(TAG, "Failed to disconnect from broker: " + e.getMessage());}}/*** 连接状态反馈* @return true连接,false断开*/public boolean isConnect() {if (client.isConnected()) {Log.i(TAG, "MQTT连接成功");return true;} else {Log.i(TAG, "MQTT连接断开");return false;}}}
二、调用工具类实现通信
1. 连接
String brokerUrl,clientId,username,password;
//相关参数赋值
mqttService = new MqttService(this, brokerUrl, clientId, username, password);
// 连接MQTT
mqttService.connect();
2. 订阅
String subTopic = "订阅的主题";
mqttService.subscribe(subTopic);
3. 发布
String payload = "发布内容";
String Topic = "发布主题";
mqttService.publish(Topic, payload);
4. 订阅消息接收
接收消息采用广播的方式进行接收
@Overrideprotected void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);setContentView(R.layout.activity_main);//接收广播消息IntentFilter filter = new IntentFilter("com.example.aliyuniot.MainActivity");registerReceiver(myReceiver, filter);}private BroadcastReceiver myReceiver = new BroadcastReceiver(){@Overridepublic void onReceive(Context context, Intent intent) {String action = intent.getAction();if (action.equals("com.example.aliyuniot.MainActivity")) {String message = intent.getStringExtra("message");tev_subrecv.setText(message);}}};
三、测试——以阿里云物联网平台为例
1. 连接断开
2. 订阅
采用云产品消息流转,用MQTT.fx模拟设备上报属性。
3. 发布
apk安装包:https://download.csdn.net/download/LJ_96/89879415
源码地址:https://download.csdn.net/download/LJ_96/89879421