Skip to content

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 ​

Android / Kotlin app connecting to ConnectMQ A Android / Kotlin app uses HiveMQ MQTT client (open source) to connect to broker.connectmq.com over MQTT 5 · TLS 8883 with a username, password and a client ID based on the issued client ID. The broker checks the client with the Broker API (credentials, client ID, ACL and plan limits) and delivers messages to the web console and other devices and services. Your codeEveryone else on the brokerConnectMQ CloudMQTT 5 · TLS 8883username · password · client ID <ISSUED_ID>_<suffix>authAndroid / Kotlin appHiveMQ MQTT client (open source)client.publishWith().topic(…).qos(MqttQos.AT_LEAST_ONCE).payload(…).send()Android apps and Kotlin servicesMQTT brokerbroker.connectmq.comTLS 8883 · WSS 8084 /mqtt · MQTT 3.1.1 and 5Broker APICredentials · client IDACL · plan limitsWeb consoleapp.connectmq.com · live topics · alertsDevices & servicesESP32 · ConnectMQ Edge · back ends · appsMQTT messagesConnection check (credentials, client ID, ACL)

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() and subscribeWith().
  • Try without an account: connect to broker.connectmq.com on port 1883 without TLS and credentials. The public test broker is readable by anyone, so use it for experiments only.

Fully managed MQTT broker for connected devices.