Android MQTT开发之 Hivemq MQTT Client

使用一个开源库:hivemq-mqtt-client,这是Java生态的一个MQTT客户端框架,需要Java 8,Android上使用的话问题不大,需要一些额外的配置,下面列出了相关的配置,尤其是 packagingOptions,不然编译不过,因为框架使用了Java8新增的语言特性,所以 minSdk 设置为24,即Android7.0,如果要兼容Android7.0以下系统,可以参考这份详细文档配置一下语法脱糖的SDK:Installation on Android

Groovy 复制代码
android {
    defaultConfig {
        minSdk 24
    }
    compileOptions {
        sourceCompatibility JavaVersion.VERSION_8
        targetCompatibility JavaVersion.VERSION_8
    }
    kotlinOptions {
        jvmTarget = '8'
    }
    packagingOptions {
        resources {
            excludes += ['META-INF/INDEX.LIST', 'META-INF/io.netty.versions.properties']
        }
    }
}

dependencies {
    implementation 'com.hivemq:hivemq-mqtt-client:1.3.3'
}

刚开始在自动连接这块花了好多时间,最后才发现是设置用户名和密码的地方不对,一定要在设置自动重连(初始化Client)的地方设置,而不是连接的时候!下面是一个简单的使用示例代码

MqttManager.kt

Kotlin 复制代码
import android.util.Log
import com.hivemq.client.mqtt.datatypes.MqttQos
import com.hivemq.client.mqtt.lifecycle.MqttClientConnectedContext
import com.hivemq.client.mqtt.lifecycle.MqttClientConnectedListener
import com.hivemq.client.mqtt.lifecycle.MqttClientDisconnectedContext
import com.hivemq.client.mqtt.lifecycle.MqttClientDisconnectedListener
import com.hivemq.client.mqtt.mqtt5.Mqtt5AsyncClient
import com.hivemq.client.mqtt.mqtt5.Mqtt5Client
import com.hivemq.client.mqtt.mqtt5.message.connect.connack.Mqtt5ConnAckReasonCode
import com.hivemq.client.mqtt.mqtt5.message.publish.Mqtt5Publish
import com.hivemq.client.mqtt.mqtt5.message.subscribe.suback.Mqtt5SubAck
import java.util.UUID
import java.util.concurrent.CompletableFuture
import java.util.concurrent.Executors
import java.util.function.Consumer

open class MqttListener {
    open fun onConnected() {}
    open fun onDisconnected() {}
    open fun onSubscribed(vararg topics: String) {}
    open fun onReceiveMessage(topic: String, data: ByteArray) {}
    open fun onSendMessage(topic: String, data: ByteArray) {}
}

/*
文档
https://github.com/hivemq/hivemq-mqtt-client
https://hivemq.github.io/hivemq-mqtt-client/docs/installation/android/
*/
class MqttManager private constructor() : MqttClientConnectedListener, MqttClientDisconnectedListener {
    private val executor = Executors.newFixedThreadPool(Runtime.getRuntime().availableProcessors()) {
        Thread(it).apply { isDaemon = true }
    }

    private val mqttAsynClient: Mqtt5AsyncClient = Mqtt5Client.builder()
        .identifier(UUID.randomUUID().toString())
        .serverHost(SERVER_HOST)
        .serverPort(SERVER_PORT)
        .addConnectedListener(this)
        .addDisconnectedListener(this)
        .simpleAuth()//在初始化的时候设置账号密码,重连才能成功
        .username(USERNAME)
        .password(PASSWORD.toByteArray())
        .applySimpleAuth()
        .automaticReconnectWithDefaultConfig()//自动重连
        .buildAsync()

    private val listeners = mutableListOf<MqttListener>()

    private val subTopics
        get() = arrayOf("top1", "top2", "top3")

    fun addMqttListener(listener: MqttListener) {
        if (!listeners.contains(listener)) {
            listeners.add(listener)
        }
    }

    fun removeMqttListener(listener: MqttListener) {
        listeners.remove(listener)
    }

    override fun onConnected(context: MqttClientConnectedContext) {
        Log.i(TAG, "onConnected()")
        for (l in listeners) {
            l.onConnected()
        }
        subscribeAll()
    }

    private fun subscribeAll() {
        CompletableFuture.supplyAsync({
            val futures = subTopics.map(::subscribe)
                .map {
                    it.thenCompose {
                        CompletableFuture.supplyAsync({
                            val success = !it.reasonString.isPresent
                            if (success) {
                                Log.i(TAG, "subscribe success")
                            } else {
                                Log.e(
                                    TAG, "subscribe() - reasonCodes=[${it.reasonCodes.joinToString(", ")}]" +
                                            ", reasonString=${it.reasonString}"
                                )
                            }
                            success
                        }, executor)
                    }
                }
                .toTypedArray()
            CompletableFuture.allOf(*futures).join()//等待所有订阅结果
            if(futures.all { it.get() }) {
                Log.i(TAG, "subscribeAll() - 全部订阅成功")
            }
            for (l in listeners) {
                l.onSubscribed(*subTopics)
            }
        }, executor)
    }

    override fun onDisconnected(context: MqttClientDisconnectedContext) {
        Log.e(
            TAG, "onDisconnected() - isConnected=${mqttAsynClient.state.isConnected}" +
                    ", isConnectedOrReconnect=${mqttAsynClient.state.isConnectedOrReconnect}"
        )
        for (l in listeners) {
            l.onDisconnected()
        }
    }

    fun connect() {
        mqttAsynClient
            .connectWith()
            .cleanStart(true)
            .keepAlive(30)
            .send()
            .thenAccept {
                if (it.reasonCode == Mqtt5ConnAckReasonCode.SUCCESS) {
                    Log.i(TAG, "connect() - SUCCESS")
                } else {
                    Log.e(TAG, "connect() - ${it.reasonCode}")
                }
            }
    }

    fun disconnect() {
        mqttAsynClient.disconnect().thenAccept {
            Log.i(TAG, "disconnect()")
        }
    }


    private val callback = Consumer<Mqtt5Publish> {
        val topic = it.topic.toString()
        val data = it.payloadAsBytes
        processReceivedMessage(topic, data)
    }

    private fun processReceivedMessage(topic: String, data: ByteArray) {
        //处理接收的数据
        for (l in listeners) {
            l.onReceiveMessage(topic, data)
        }
    }

    fun subscribe(topic: String): CompletableFuture<Mqtt5SubAck> {
        return mqttAsynClient.subscribeWith()
            .topicFilter(topic)
            .noLocal(true)// we do not want to receive our own message
            .qos(MqttQos.AT_MOST_ONCE)
            .callback(callback)
            .executor(executor)
            .send()
    }

    fun unsubscribe(topic: String) {
        mqttAsynClient.unsubscribeWith()
            .topicFilter(topic)
            .send().thenAccept {
                Log.i(TAG, "unsubscribe() - $it")
            }
    }

    /**
     * 发送数据
     */
    fun publish(topic: String, payload: ByteArray) {
        mqttAsynClient.publishWith()
            .topic(topic)
            .qos(MqttQos.AT_MOST_ONCE)
            .payload(payload)
            .send()
            .thenAccept { mqtt5PublishResult ->
                mqtt5PublishResult.publish.let { mqtt5Publish ->
//                    val topic = mqtt5Publish.topic.toString()
                    val data = mqtt5Publish.payloadAsBytes
                    for (l in listeners) {
                        l.onSendMessage(topic, data)
                    }
                }
            }
    }

    companion object {
        private const val TAG = "MqttManager"

        private const val SERVER_HOST = "example.com"
        private const val SERVER_PORT = 1883 // 1883即TCP协议,host不要再加上"tcp://",否则连不成功
        private const val USERNAME = "admin"
        private const val PASSWORD = "123456"

        val instance = MqttManager()
    }
}
相关推荐
数据猎手小k3 小时前
AndroidLab:一个系统化的Android代理框架,包含操作环境和可复现的基准测试,支持大型语言模型和多模态模型。
android·人工智能·机器学习·语言模型
你的小104 小时前
JavaWeb项目-----博客系统
android
风和先行4 小时前
adb 命令查看设备存储占用情况
android·adb
AaVictory.5 小时前
Android 开发 Java中 list实现 按照时间格式 yyyy-MM-dd HH:mm 顺序
android·java·list
似霰6 小时前
安卓智能指针sp、wp、RefBase浅析
android·c++·binder
大风起兮云飞扬丶6 小时前
Android——网络请求
android
干一行,爱一行6 小时前
android camera data -> surface 显示
android
断墨先生6 小时前
uniapp—android原生插件开发(3Android真机调试)
android·uni-app
无极程序员8 小时前
PHP常量
android·ide·android studio
萌面小侠Plus9 小时前
Android笔记(三十三):封装设备性能级别判断工具——低端机还是高端机
android·性能优化·kotlin·工具类·低端机