mqtt安卓客户端

1.MQTT(消息队列遥测传输协议),是一种基于 发布/订阅 (publish/subscribe)模式的"轻量级"通讯协议, 该协议构建于TCP/IP协议上 。MQTT最大优点在于,可以以极少的代码和有限的带宽,为连接远程设备提供实时可靠的消息服务。作为一种低开销、低带宽占用的即时通讯协议,使其在物联网、小型设备、移动应用等方面有较广泛的应用。

MQTT协议中有三种身份:发布者(Publish)、服务器(Broker)、订阅者(Subscribe)

2.api操作:

Connect:与服务器进行MQTT连接;

Disconnect:与服务器断开MQTT连接;

Subscribe:订阅某个主题;

UnSubscribe:取消订阅某个主题;

Publish:发布消息;

3.安卓客户端示例:

添加依赖:

java 复制代码
    implementation 'org.eclipse.paho:org.eclipse.paho.client.mqttv3:1.2.2'
    implementation 'org.eclipse.paho:org.eclipse.paho.android.service:1.1.1'

添加权限

java 复制代码
<uses-permission android:name="android.permission.INTERNET" />

java代码

java 复制代码
//创建实例
//brokerUrl为实例,clientid是唯一值
MqttAndroidClient mqttAndroidClient = new MqttAndroidClient(context, brokerUrl, clientId);

 //设置监听订阅消息的回调
        mqttAndroidClient.setCallback(mqttCallback);
        mMqttConnectOptions = new MqttConnectOptions();
        //设置是否清除缓存
        mMqttConnectOptions.setCleanSession(true);
        //设置超时时间,单位:秒
        mMqttConnectOptions.setConnectionTimeout(60);
        //设置心跳包发送间隔,单位:秒
        mMqttConnectOptions.setKeepAliveInterval(60);
        //设置用户名
        mMqttConnectOptions.setUserName(userName);
        //设置密码
        mMqttConnectOptions.setPassword(password.toCharArray());
        //是否重连
        mMqttConnectOptions.setAutomaticReconnect(false);
        //同时发布的最大消息数量
        mMqttConnectOptions.setMaxInflight(10000);

//建立连接
 mqttAndroidClient.connect(mMqttConnectOptions, null, iMqttActionListener);

  private final MqttCallback mqttCallback = new MqttCallback() {

           //这里处理收到的数据
        @Override
        public void messageArrived(String topic, MqttMessage message) {
       
        }

        @Override
        public void deliveryComplete(IMqttDeliveryToken arg0) {
            Log.d(TAG, "deliveryComplete: ");
        }

        @Override
        public void connectionLost(Throwable arg0) {
            Log.e(TAG, "connectionLost:" + arg0.getMessage());
            Log.e(TAG, "onFailure: " + mqttAndroidClient.isConnected());
            doReconnect();
        }

    };


 private final IMqttActionListener iMqttActionListener = new IMqttActionListener() {
        @Override
        public void onSuccess(IMqttToken arg0) {
           //建立订阅
            try {
                mqttAndroidClient.subscribe(topic, topicQos, null,
                        new IMqttActionListener() {
                            @Override
                            public void onSuccess(IMqttToken asyncActionToken) {
                                Log.d(TAG, "Subscribed topic successfully: " + asyncActionToken
                                        .toString());
                            }

                            @Override
                            public void onFailure(IMqttToken asyncActionToken,
                                                  Throwable exception) {
                                Log.d(TAG, "Failed to subscribe to a topic: " + asyncActionToken
                                        .toString());
                            }

                        });
            } catch (MqttException e) {
                Log.d(TAG, "Subscribe to the topic: " + e);
                e.printStackTrace();
            }
        }

        @Override
        public void onFailure(IMqttToken arg0, Throwable arg1) {
            arg1.printStackTrace();
            Log.e(TAG, "iMqttActionListener: arg0:" + arg0.toString() + " arg1:" + arg1
                    .getMessage());
            Log.e(TAG, "onFailure: " + mqttAndroidClient.isConnected());
            doReconnect();
        }
    };



MqttMessage message = new MqttMessage();
            message.setPayload(payload.getBytes());
            message.setQos(0);

//publish到mqtt
 mqttAndroidClient.publish(mTopic, message, null, new IMqttActionListener() {
                @Override
                public void onSuccess(IMqttToken asyncActionToken) {
                    Log.i(TAG, "publish succeed!");
                    listener.onState(1);
                }

                @Override
                public void onFailure(IMqttToken asyncActionToken, Throwable exception) {
                    Log.i(TAG, "publish failed!");
                    listener.onState(2);
                }
            });
相关推荐
IT界的奇葩3 天前
MQTT+Disruptor 提高物联网高并发
java·物联网·mqtt·springboot·disruptor
香菜+6 天前
unity 中使用zeroMq和Mqtt 进行通讯
mqtt·unity·emqx·zeromq
linmoo19867 天前
java脚手架系列13-IoT
java·mqtt·iot·emqx·脚手架
青山师10 天前
Mqtt协议快速入门Demo
物联网·mqtt
昵称p13 天前
lvgl
mcu·mqtt·操作系统·lvgl·任务创建
迷途的少年19 天前
JMeter之mqtt-jmeter 插件介绍
mqtt·jmeter
serene9421 天前
第二章:信息建模:对象和变量的类型2
物联网·mqtt·modbus·opc·opc ua·iec 104
沃和莱特25 天前
EMQX服务器的搭建,实现本地机和虚拟机之间的MQTT通信(详细教程)
运维·mqtt·ubuntu·运维开发·emqx·通信协议
「QT(C++)开发工程师」25 天前
STM32 | MQTT+esp8266(第十四天)
linux·c++·stm32·单片机·mqtt
「QT(C++)开发工程师」25 天前
STM32 | STM32F4OTA_ESP8266_Bootloader为引导程序远程更新的代码(APP)
stm32·单片机·嵌入式硬件·mqtt·wifi