1. implementation
implementation 'org.eclipse.paho:org.eclipse.paho.client.mqttv3:1.2.5'
implementation 'org.eclipse.paho:org.eclipse.paho.android.service:1.1.1'
2. mqtt establish
import org.eclipse.paho.android.service.MqttAndroidClient
import org.eclipse.paho.client.mqttv3.*
val brokerUrl = "tcp://your-mqtt-broker-url"
val clientId = MqttClient.generateClientId()
val mqttClient = MqttAndroidClient(applicationContext, brokerUrl, clientId)
val mqttOptions = MqttConnectOptions()
mqttOptions.isCleanSession = true
mqttClient.connect(mqttOptions, null, object : IMqttActionListener {
override fun onSuccess(asyncActionToken: IMqttToken?) {
}
override fun onFailure(asyncActionToken: IMqttToken?, exception: Throwable?) {
}
})
3. publish
val latitude = 37.1234
val longitude = -122.5678
val topic = "location/topic"
val payload = "{\"latitude\": $latitude, \"longitude\": $longitude}"
val message = MqttMessage(payload.toByteArray())
message.qos = 1
mqttClient.publish(topic, message)
4. disconnect
mqttClient.disconnect()