MainActivity.kt
package ee.ut.cs.lab11alpha
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() {
// 10.0.2.2 refers to host machine from Android emulator
// If you are not using an emulator, you will have to specify a 'real' ip. See
//https://developer.android.com/studio/run/emulator-networking.html for more
private val MQTT_BROKER_IP = "tcp://10.0.2.2:1883"
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()
}
}