我一直在尝试在我的 Android 应用程序中使用 hivemq 实现 mqtt。尽管我使用了他们文档中的相同规格和配置,但我仍然无法建立成功的连接。
我之前能够将 paho 用于 mqtt,但如果应用程序处于后台,则它不适用于 android Oreo 及更高版本,因为该库没有 startServiceForeground 更新。因此转移到 HiveMq。我只是使用此处的快速入门指南尝试他们的示例应用程序。1. https://hivemq.github.io/hivemq-mqtt-client/ 2. https://www.hivemq.com/blog/mqtt-client-library-enyclopedia-hivemq-mqtt-client/ 3. https: //github.com/hivemq/hivemq-mqtt-client/blob/develop/README.md 几乎浪费了一天的时间来弄清楚如何连接到他们的 mqtt,但不成功
lateinit var client : Mqtt3Client
fun connect() {
client = Mqtt3Client.builder()
.identifier(UUID.randomUUID().toString())
.serverHost("broker.hivemq.com")
.serverPort(1883)
.buildAsync()
client.toAsync().connect()
.whenComplete { mqtt3ConnAck, throwable ->
if (throwable != null) {
// handle failure
android.util.Log.v("HIVE-MQTT-LCDP", " connection failed")
} else {
android.util.Log.v("HIVE-MQTT-LCDP", " connected")
// setup subscribes or start publishing
subscribe()
publish()
}
}
fab.setOnLongClickListener {
android.util.Log.v("HIVE-MQTT-LCDP", " disconnected")
client.toAsync().disconnect()
true …Run Code Online (Sandbox Code Playgroud)