当前位置: 首页 > article >正文

Android MQTT调试助手开发

        在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() {
                @Override
                public void connectionLost(Throwable cause) {
                    Log.e(TAG, "Connection lost: " + cause.getMessage());
                }

                @Override
                public 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()));
                }

                @Override
                public 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. 订阅消息接收

接收消息采用广播的方式进行接收

@Override
    protected 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(){
        @Override
        public 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


http://www.kler.cn/news/353579.html

相关文章:

  • Spring Boot学习助手:答疑解惑平台
  • 蛮久没更新自己的状态了,今天趁机更新一下吧
  • 【手写数字识别】Python+CNN卷积神经网络算法+人工智能+深度学习+模型训练
  • 【Python】Conda离线执行命令
  • 架构师之路-学渣到学霸历程-19
  • react hooks中在setState后输出state为啥没有变化,如何解决
  • SpringBoot概览及核心原理
  • 深入解析 Flutter兼容鸿蒙next全体生态的横竖屏适配与多屏协作兼容架构
  • 高效录制 PPT 秘籍:四款卓越录屏软件深度解析
  • 插齿刀的齿数选择不同会有什么影响?
  • 公网IP and 局域网IP
  • 网页复制粘贴助手,Chrome网页复制插件(谷歌浏览器复制插件)
  • servlet基础与环境搭建(idea版)
  • 解决 MySQL 连接数过多导致的 SQLNonTransientConnectionException 问题
  • 25四非网安保研回忆录(北航网安/东南网安/重大计科等)
  • 更加灵活便捷!Fortinet统一SASE解决方案全新增强功能来袭
  • sql数据库命令行操作(数据库的增删改查)
  • Git客户端使用之TortoiseGit和Git
  • 【EI会议征稿 | 往届会后三个月内见刊、检索】第四届高性能计算与通信工程国际学术会议(HPCCE 2024)
  • vue axios表单提交