MainActivity.kt
import android.os.Bundle
import android.util.Log
import androidx.appcompat.app.AppCompatActivity
import org.eclipse.paho.android.service.MqttAndroidClient
import org.eclipse.paho.client.mqttv3.IMqttDeliveryToken
import org.eclipse.paho.client.mqttv3.MqttCallbackExtended
import org.eclipse.paho.client.mqttv3.MqttMessage
class MainActivity : AppCompatActivity() {
    private val MQTT_BROKER_IP = "tcp://x.x.x.x:1883" // TODO
    // Note: If you want to use emulator, and access a broker running on the emulators host (your laptop), 
    // then use the IP: 10.0.2.2 - it refers to host machine from Android emulator
    // In other cases, you will have to specify a 'real' ip. See
    //https://developer.android.com/studio/run/emulator-networking.html for more
    val TAG = "MqttActivity"
    lateinit var mqttClient: MqttAndroidClient
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
        // set up client
        mqttClient = MqttAndroidClient(this, MQTT_BROKER_IP, "lab11client")
        mqttClient.setCallback(object : MqttCallbackExtended {
            override fun connectComplete(reconnect: Boolean, serverURI: String?) {
                Log.i(TAG, "MQTT Connected")
                //TODO: subscribe to a topic
            }
            override fun messageArrived(topic: String?, message: MqttMessage?) {
                Log.i(TAG, "MQTT Message: $topic, msg: ${message.toString()}")
            }
            override fun connectionLost(cause: Throwable?) {
                Log.i(TAG, "MQTT Connection Lost!")
            }
            override fun deliveryComplete(token: IMqttDeliveryToken?) {
                Log.i(TAG, "MQTT Message Delivered!")
            }
        })
        mqttClient.connect()    //  Can also specify options, e.g. :  mqttClient.connect( MqttConnectOptions().apply { isAutomaticReconnect=true } )
    }
    override fun onDestroy() {
        mqttClient.disconnect()
        super.onDestroy()
    }
}