paho.mqtt.android Documentation

repository·master·Indexed 20 days ago

https://github.com/hannesa2/paho.mqtt.android

A Kotlin-based MQTT client library for Android designed for M2M and IoT applications. It provides reliable messaging and background connectivity, with version 4.x utilizing androidx.work for battery-optimized message reception and version 3.x supporting foreground services. The library includes features for SSL/TLS configuration via BKS keystores, manual message acknowledgment, and asynchronous event handling through MqttCallback.

Tokens
3.7K
Snippets
16
Records
19
Agent score
70%

What's inside paho.mqtt.android

  1. Understand background behavior and service requirements

    master

    The library's background behavior depends on the major version used:

    • No foreground service required: It does not use android.permission.SCHEDULE_EXACT_ALARM, which helps prevent battery drain.
    • Reliable message reception: It utilizes androidx.work:work-runtime-ktx to ensure messages are received even during device sleep.

    Version 3.x

    • Foreground service required: On Android O (API 26) and higher, you must explicitly set it as a foreground service to maintain connectivity.
  2. Install the MQTT Android Client via JitPack

    master

    To use this library, add the JitPack repository to your project's allprojects block and then add the dependency to your dependencies block. Replace $latestVersion with the desired version number.

    allprojects {
      repositories {
        ...
        maven { url 'https://jitpack.io' }
      }
    }
    
    dependencies {
      implementation "com.github.hannesa2:paho.mqtt.android:$latestVersion"
    }
  3. Extract certificates from an MQTT broker

    master

    To use SSL/TLS with an MQTT broker, you may need to extract its certificate chain. You can use openssl to connect to the broker and pipe the certificate output to a .crt file.

    Note: You must capture all certificates in the chain. If there are multiple certificates, copy each one into its own .crt file.

    echo -n | openssl s_client -connect broker.hivemq.com:8883 | sed -ne '/-BEGIN CERTIFICATE-/,/-END CERTIFICATE-/p' > eclipse.crt
  4. List certificates in a BKS keystore

    master

    To verify the contents of your BKS keystore, use the keytool -list command. This allows you to confirm that the certificates were added correctly with the expected aliases.

    keytool -list -v -keystore test.bks -provider org.bouncycastle.jce.provider.BouncyCastleProvider -providerpath "./bcprov-jdk15on-1.65.jar" -storetype BKS -storepass mqtttest
  5. Add certificates to a BKS keystore

    master

    To create or update a Bouncy Castle Keystore (BKS) for use in the Android MQTT client, use the keytool command. You must specify the BouncyCastle provider and its corresponding JAR file path.

    Required parameters:

    • -storetype BKS: Specifies the Bouncy Castle Keystore format.
    • -provider org.bouncycastle.jce.provider.BouncyCastleProvider: The Bouncy Castle provider class.
    • -providerpath: The path to the bcprov-jdk15on-1.65.jar file.
    • -storepass: The password for the keystore.
    keytool -importcert -v -trustcacerts -file eclipse.crt -alias broker.hivemq.com -keystore "test.bks" -provider org.bouncycastle.jce.provider.BouncyCastleProvider -providerpath "./bcprov-jdk15on-1.65.jar" -storetype BKS -storepass mqtttest
  6. Manage client lifecycle resources

    master

    Because this library uses an Android Service, you must manage the registration of resources to avoid memory leaks and ensure the service connection is maintained correctly.

    • registerResources(): Call this when your Activity/Component becomes visible to ensure the service is bound and intents are being collected.
    • unregisterResources(): Call this when your Activity/Component is hidden or destroyed to unbind from the service and cancel background jobs.
  7. Configure a foreground service for Version 3.x

    master

    If you are using version 3.x on Android O or higher, you must call setForegroundService on your MqttAndroidClient instance using a notification and a service type (e.g., 3).

    val client = MqttAndroidClient(context, uri, clientId).apply {
        setForegroundService(foregroundNotification, 3)
    }
  8. Retrieve pending delivery tokens

    master

    If a client restarts and there are messages that were in the process of being delivered when the client stopped, you can retrieve their delivery tokens using getPendingDeliveryTokens().

    Note: This only works if the client connects with cleanSession set to false. If cleanSession is true, all earlier state is deleted and no pending tokens will be returned.

    val pendingTokens = client.getPendingDeliveryTokens()
    for (token in pendingTokens) {
        // Track in-flight messages
    }
  9. Manage asynchronous event callbacks

    master

    To handle asynchronous MQTT events like incoming messages, connection loss, or message delivery completion, you must register a MqttCallback with the client.

    • setCallback(callback: MqttCallback): Sets a single callback listener. This replaces any existing callback.
    • addCallback(callback: MqttCallback): Adds an additional callback listener to the existing list.
    • removeCallback(callback: MqttCallback): Removes a specific callback listener.

    Common events handled by MqttCallback include:

    • messageArrived: A new message has arrived.
    • connectionLost: The connection to the server was lost.
    • deliveryComplete: A message was successfully delivered to the server.
    client.setCallback(object : MqttCallback {
        override fun messageArrived(topic: String, message: MqttMessage) {
            // Handle incoming message
        }
        override fun connectionLost(cause: Throwable?) {
            // Handle connection loss
        }
        override fun deliveryComplete(token: IMqttDeliveryToken) {
            // Handle delivery completion
        }
    }) 
  10. Configure manual message acknowledgment

    master

    When using manual acknowledgment mode, you must explicitly acknowledge a message after processing it to prevent the server from re-sending it.

    To acknowledge a message, use acknowledgeMessage(messageId: String). You can obtain the messageId from the MqttMessage by casting it to ParcelableMqttMessage.

    // Inside messageArrived callback
    val messageId = (message as ParcelableMqttMessage).messageId
    val success = client.acknowledgeMessage(messageId)
  11. Create an SSLSocketFactory for secure connections

    master

    The getSSLSocketFactory method provides a convenience way to generate an SSLSocketFactory using a provided KeyStore and password. This is useful for connecting to servers that require SSL/TLS authentication.

    Throws: MqttSecurityException if there is an error during KeyStore loading or SSL context initialization.

    val sslSocketFactory = client.getSSLSocketFactory(keyStoreInputStream, "your_password")
    // Use this factory in your connection options
  12. Enable and configure tracing

    master

    The client supports tracing for debugging purposes. You can enable/disable tracing and provide a custom handler to process trace events.

    • setTraceEnabled(traceEnabled: Boolean): Enables or disables tracing.
    • setTraceCallback(traceCallback: MqttTraceHandler?): Sets a handler to receive trace events (Debug, Error, or Exceptions).
    • setTraceCallback(traceCallback: MqttTraceHandler?): Sets a handler to receive trace events (Debug, Error, or Exceptions).