工作笔记:Android中MQTT使用说明

MQTT使用说明

注:如果是直接用我的MVVM-base,那直接添加lib-network模块进行使用即可

添加依赖

// mqtt 相关类库
implementation 'org.eclipse.paho:org.eclipse.paho.android.service:1.1.1'
implementation 'org.eclipse.paho:org.eclipse.paho.client.mqttv3:1.1.1'

AndroidManifest中添加service

<service android:name="org.eclipse.paho.android.service.MqttService" />

调用

//mqtt使用例子
var mqtt=MQTTClient.newInstance(this)
mqtt.setOnCallback(object :MqttClientCallBack{
    override fun onMessageReceive(message: String?) {
    }
})
//关闭mqtt
mqtt.stop()

核心代码块

package com.yangchoi.lib_network.mqtt


import android.annotation.SuppressLint
import android.content.Context
import android.util.Log
import org.eclipse.paho.android.service.MqttAndroidClient
import org.eclipse.paho.client.mqttv3.*


/**
 *    author : 吴明辉
 *    e-mail : 1412378121@qq.com
 *    date   : 2022/3/2510:43
 *    git    : https://gitee.com/yunianvh
 *    desc   : mqtt工具类
 */
@SuppressLint("MissingPermission")
class MQTTClient private constructor(context: Context) {

    /**
     * 连接MQTT服务器
     */
    private fun doClientConnection() {
        client?.let { client ->
            if (!client.isConnected) {
                try {
                    client.connect(conOpt, null, iMqttActionListener)
                } catch (e: MqttException) {
                    Log.e(TAG, "$e")
                }
            }
        }
    }

    /**
     * MQTT是否连接成功回调方法
     */
    private val iMqttActionListener: IMqttActionListener = object : IMqttActionListener {
        override fun onSuccess(arg0: IMqttToken) {
            Log.i(TAG, "连接成功 ")
            try { // 订阅myTopic话题
                client?.subscribe(Constant.MQ.subscribeTopic, 1)
            } catch (e: MqttException) {
                Log.e(TAG, "$e")
            }
        }

        override fun onFailure(asyncActionToken: IMqttToken, exception: Throwable) {
            Log.e(TAG, "$exception")
            // 连接失败,重连
        }
    }

    /**
     * MQTT接收消息回调
     */
    private val mqttCallback: MqttCallback = object : MqttCallback {
        @Throws(Exception::class)
        override fun messageArrived(topic: String, message: MqttMessage) {
            val str1 = String(message.payload)
            mMqttServiceCallback?.onMessageReceive(str1)
            val str2 = topic + ";qos:" + message.qos + ";retained:" + message.isRetained
            Log.i(TAG, "messageArrived:$str1")
            Log.i(TAG, str2)
        }

        override fun deliveryComplete(token: IMqttDeliveryToken?) {
            Log.i(TAG, "$token")
        }

        override fun connectionLost(cause: Throwable?) {
            // 失去连接,重连
            Log.e(TAG, "$cause")
        }
    }

    /**
     * 关闭MQTT
     */
    fun stop() {
        if (client == null || client?.isConnected == false) return
        try {
            client!!.disconnect()
        } catch (e: MqttException) {
            e.printStackTrace()
        } catch (e: NullPointerException) {
            e.printStackTrace()
        }
    }

    /**
     * 设置回调监听
     */
    fun setOnCallback(mqttCallBack: MqttClientCallBack) {
        mMqttServiceCallback = mqttCallBack
    }

    /**
     * 发送消息
     */
    fun publish(msg: String) {
        if (client == null || msg.isBlank()) return
        try {
            client?.publish(Constant.MQ.publishTopic, msg.toByteArray(), 0, false)
        } catch (e: MqttException) {
            Log.e(TAG, "$e")
        }
    }

    companion object {
        fun newInstance(context: Context): MQTTClient {
            return MQTTClient(context)
        }

        private val TAG = MQTTClient::class.java.simpleName
        private var conOpt: MqttConnectOptions? = null
        private var client: MqttAndroidClient? = null
        private var mMqttServiceCallback: MqttClientCallBack? = null
    }

    init { // 服务器地址(协议+地址+端口号)
        val uri = Constant.MQ.host
        client = MqttAndroidClient(context, uri, Constant.MQ.clientId)
        // 设置MQTT监听并且接受消息
        client?.setCallback(mqttCallback)
        conOpt = MqttConnectOptions()
        conOpt?.apply {
            // 清除缓存
            isCleanSession = true
            // 设置超时时间,单位:秒
            connectionTimeout = 10
            // 心跳包发送间隔,单位:秒
            keepAliveInterval = 20
            // 用户名
            userName = Constant.MQ.userName
            // 密码
            password = Constant.MQ.passWord.toCharArray() //将字符串转换为字符串数组
        }
        // last will message
        var doConnect = true
        val message = "{\"terminal_uid\":\"${Constant.MQ.clientId}\"}"
        Log.e(TAG, "message是:$message")
        val topic = Constant.MQ.subscribeTopic
        val qos = 0
        val retained = false
        try {
            conOpt?.setWill(topic, message.toByteArray(), qos, retained)
        } catch (e: Exception) {
            Log.i(TAG, "Exception Occured", e)
            doConnect = false
            iMqttActionListener.onFailure(null, e)
        }
        if (doConnect) {
            doClientConnection()
        }
    }
}

基本配置信息

package com.yangchoi.lib_network.mqtt

/**
 *    author : 吴明辉
 *    e-mail : 1412378121@qq.com
 *    date   : 2022/3/2510:47
 *    git    : https://gitee.com/yunianvh
 *    desc   :
 */
object Constant {
    object MQ {
        const val host = "tcp://192.168.0.111:61613"
        const val userName = "admin"
        const val passWord = "password"
        const val clientId = "androidId" //客户端标识
        const val subscribeTopic = "client2_1" //要订阅的主题
        const val publishTopic = "client1_2" //要发布的主题
    }
}

回调接口

package com.yangchoi.lib_network.mqtt

/**
 *    author : 吴明辉
 *    e-mail : 1412378121@qq.com
 *    date   : 2022/3/2510:46
 *    git    : https://gitee.com/yunianvh
 *    desc   :
 */
interface MqttClientCallBack {
    fun onMessageReceive(message: String?)
}
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

玉念聿辉

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值