android mqtt(轻量级物联网消息推送)

MQTT是机器对机器(M2M)/物联网(IoT)连接协议。它被设计为一个极其轻量级的发布/订阅消息传输协议。对于需要较小代码占用空间和/或网络带宽非常宝贵的远程连接非常有用,是专为受限设备和低带宽、高延迟或不可靠的网络而设计。这些原则也使该协议成为新兴的“机器到机器”(M2M)或物联网(IoT)世界的连接设备,以及带宽和电池功率非常高的移动应用的理想选择。例如,它已被用于通过卫星链路与代理通信的传感器、与医疗服务提供者的拨号连接,以及一系列家庭自动化和小型设备场景。它也是移动应用的理想选择,因为它体积小,功耗低,数据包最小,并且可以有效地将信息分配给一个或多个接收器。

特点

  • 开放消息协议,简单易实现
  • 发布订阅模式,一对多消息发布
  • 基于TCP/IP网络连接,提供有序,无损,双向连接。
  • 1字节固定报头,2字节心跳报文,最小化传输开销和协议交换,有效减少网络流量。
  • 消息QoS支持,可靠传输保证

接下来主要应用于Android中的使用。

1.build.gradle中引入一下包,使项目能正常使用mqtt:

implementation 'org.eclipse.paho:org.eclipse.paho.client.mqttv3:1.1.0'
implementation 'org.eclipse.paho:org.eclipse.paho.android.service:1.1.1'

 2.设置mqtt连接服务器

//连接到服务器
    public void connectMQTT(String host, String port, String clientId, String userName, String token, IMqttActionListener callBack) {
        mMqttClient = new MqttAndroidClient(context, String.format("tcp://%s:%s", host, port), clientId);
        //连接参数
        MqttConnectOptions options;
        options = new MqttConnectOptions();
        //设置自动重连
        options.setAutomaticReconnect(true);
        // 缓存
        options.setCleanSession(true);
        // 设置超时时间,单位:秒
        options.setConnectionTimeout(300);
        // 心跳包发送间隔,单位:秒
        options.setKeepAliveInterval(45);
        // 用户名
        options.setUserName(userName);
        // 密码
        options.setPassword(token.toCharArray());
        options.setMqttVersion(MqttConnectOptions.MQTT_VERSION_3_1_1);
        // 设置MQTT监听
        mMqttClient.setCallback(new MqttCallback() {
            @Override
            public void connectionLost(Throwable cause) {
                Log.d(TAG, "connectionLost: 连接断开");
                mqttListener.onConnectionLost(cause);
            }

            @Override
            public void messageArrived(String topic, MqttMessage message) throws Exception {
                Log.d(TAG, "收到消息:" + message.toString());
                mqttListener.onMessageArrived(topic, message);
            }

            @Override
            public void deliveryComplete(IMqttDeliveryToken token) {
                mqttListener.onDeliveryComplete(token);
            }
        });
        try {
            if (!mMqttClient.isConnected()) {
                //进行连接
                mMqttClient.connect(options, null, callBack);
            }
        } catch (MqttException e) {
            e.printStackTrace();
        }

    }

 3.订阅主题
 

public void subscribeMQTT(String topic, int qos, IMqttActionListener callBack) {
        try {
            //连接成功后订阅主题
            mMqttClient.subscribe(topic, qos, null, callBack);
        } catch (MqttException e) {
            e.printStackTrace();
        }

    }

4.取消订阅主题

public void unsubscribeMQTT(String topic, IMqttActionListener callBack) {
        try {
            mMqttClient.unsubscribe(topic, null, callBack);
        } catch (MqttException e) {
            e.printStackTrace();
        }
    }

5.发送消息

 public void sendMsg(String topic, String content, int qos, IMqttActionListener calBack) {
        MqttMessage msg = new MqttMessage();
        msg.setPayload(content.getBytes());//设置消息内容
        msg.setQos(qos);//设置消息发送质量,可为0,1,2.
        //设置消息的topic,并发送。
        try {
            if (mMqttClient.isConnected()) {
                mMqttClient.publish(topic, msg, null, calBack);
            }
        } catch (MqttException e) {
            e.printStackTrace();
        }
    }

 6.断开连接

public void disconnect() {
        if (mMqttClient != null && mMqttClient.isConnected()) {
            try {
                mMqttClient.disconnect();
            } catch (MqttException e) {
                e.printStackTrace();
            }
        }
    }

 7.添加监听事件

public void addMqttListener(MqttListener mqttListener) {
        this.mqttListener = mqttListener;
    }

    public interface MqttListener {
        void onSendMsgSuccess(IMqttToken asyncActionToken);

        void onSendMsgFailure(IMqttToken asyncActionToken, Throwable exception);

        void onConnectionLost(Throwable cause);

        void onMessageArrived(String topic, MqttMessage message);

        void onDeliveryComplete(IMqttDeliveryToken token);
    }

参考文献:MQTT 3.1.1 协议中文版 | MQTT中文网

  • 10
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值