Kotlin (Android)
Use the open-source HiveMQ MQTT client to connect Android apps and Kotlin services to ConnectMQ over TLS with MQTT 5.
How it connects
Install
kotlin
// build.gradle.kts (app module)
dependencies {
implementation("com.hivemq:hivemq-mqtt-client:1.3.3")
}Android apps also need the internet permission in AndroidManifest.xml:
xml
<uses-permission android:name="android.permission.INTERNET" />Publish and subscribe
kotlin
import com.hivemq.client.mqtt.datatypes.MqttQos
import com.hivemq.client.mqtt.mqtt5.Mqtt5AsyncClient
import com.hivemq.client.mqtt.mqtt5.Mqtt5Client
class TelemetryClient(issuedClientId: String, deviceSuffix: String, username: String, password: String) {
private lateinit var client: Mqtt5AsyncClient
init {
client = Mqtt5Client.builder()
.identifier("${issuedClientId}_android-$deviceSuffix") // issued client ID + "_" + suffix
.serverHost("broker.connectmq.com")
.serverPort(8883)
.sslWithDefaultConfig() // TLS: the system trust store verifies the certificate
.simpleAuth()
.username(username)
.password(password.toByteArray())
.applySimpleAuth()
.automaticReconnectWithDefaultConfig() // reconnect if the connection drops
.addConnectedListener {
// Runs after every (re)connect: a clean session has no subscriptions, so subscribe here
client.subscribeWith()
.topicFilter("acme/istanbul/#")
.qos(MqttQos.AT_LEAST_ONCE)
.callback { p -> println("${p.topic}: ${String(p.payloadAsBytes)}") }
.send()
}
.buildAsync()
}
fun connect() {
client.connect().whenComplete { _, error ->
if (error != null) println("Connect failed: ${error.message}")
}
}
fun send(temperature: Double) {
client.publishWith()
.topic("acme/istanbul/assembly/line1/tablet-01/telemetry")
.qos(MqttQos.AT_LEAST_ONCE)
.payload("""{"temperature":$temperature}""".toByteArray())
.send()
}
fun disconnect() {
client.disconnect()
}
}The async client never blocks the Android main thread. Create one TelemetryClient (for example in a ViewModel or a foreground service), call connect() once and send() whenever you have a reading. A stable deviceSuffix can be a UUID you generate on first launch and store in SharedPreferences.
Client ID and credentials in apps
- A random client ID such as
"android-" + UUID.randomUUID()is refused with Client identifier not valid (0x85). Use your issued client ID plus a suffix that is unique per installation (why). - Credentials shipped inside an app can be extracted. Create a separate credential set for the app and allow it only the topics it needs with access control (ACL).
Notes
- The same code runs on the JVM for Kotlin back-end services; use
Mqtt5Client.builder()...buildBlocking()there if you prefer blocking calls. - MQTT 5 reason codes are returned in the exceptions of
connect()andsubscribeWith(). - Try without an account: connect to
broker.connectmq.comon port 1883 without TLS and credentials. The public test broker is readable by anyone, so use it for experiments only.