CHAPTER 6 ■ IOT PATTERNS: REMOTE CONTROL
Next you are going to write code to communicate with the MQTT broker. As shown in
Figure 6-20 , right-click on the top-level package (in the example, it is com.codifythings.
lightingcontrolsystem ) and choose New ➤ Java Class.
Figure 6-21. Enter new class name
Figure 6-20. Add a new class
Enter MQTTClient in the Name field and click OK, as shown in Figure 6-21.
Android Studio will generate an empty class with the default code shown in Listing 6-8.
Listing 6-8. Default Code for MQTTClient.java
public class MQTTClient
{
...
}
Next you are going to add code to the MQTTClient that will connect and publish
to an MQTT broker whenever the user taps on the app screen. Listing 6-9 provides the
complete implementation of the MQTTClient class.
Listing 6-9. Complete Code of MQTTClient.java
package com.codifythings.lightingcontrolsystem;
import android.util.Log;
import org.eclipse.paho.client.mqttv3.MqttClient;
import org.eclipse.paho.client.mqttv3.MqttConnectOptions;
import org.eclipse.paho.client.mqttv3.MqttException;
import org.eclipse.paho.client.mqttv3.MqttMessage;
import org.eclipse.paho.client.mqttv3.persist.MemoryPersistence;