I've just started Java Android programming, or even Java programming in general and I wanted to implement the Paho MQTT Android Service using a certain MqttHandler class and I want to set the callback as a parameter for the MqttHandler class. Other answers regarding callbacks in general suggested using an interface class but I don't know how that works. This is what I have tried:
public interface InterfaceMqttCallback extends MqttCallbackExtended{
@Override
public void connectComplete(boolean b, String s);
@Override
public void connectionLost(Throwable throwable);
@Override
public void messageArrived(String topic, MqttMessage mqttMessage) throws Exception ;
@Override
public void deliveryComplete(IMqttDeliveryToken iMqttDeliveryToken);
}
the MqttHandler class constructor:
public MqttHandler(Context context, InterfaceMqttCallback mqttCallbackExtended){
mqttAndroidClient = new MqttAndroidClient(context, serverUri, clientId);
mqttAndroidClient.setCallback(mqttCallbackExtended);
connect();
}
a function in the Activity that initializes the MqttHandler:
private void startMqtt(){
mqttHandler = new MqttHandler(getApplicationContext(), new InterfaceMqttCallback() {
@Override
public void connectComplete(boolean b, String s) {
Log.w("Anjing", s);
}
@Override
public void connectionLost(Throwable throwable) {
}
@Override
public void messageArrived(String topic, MqttMessage mqttMessage) throws Exception {
Log.w("Anjing", mqttMessage.toString());
}
@Override
public void deliveryComplete(IMqttDeliveryToken iMqttDeliveryToken) {
}
});
}
But as I've tested it, I think the callbacks was not set because none of the messages have been received. So then I tried setting the callbacks directly in the MqttHandler and it works, the messages are received.
public MqttHandler(Context context, InterfaceMqttCallback mqttCallbackExtended){
mqttAndroidClient = new MqttAndroidClient(context, serverUri, clientId);
mqttAndroidClient.setCallback(new InterfaceMqttCallback() {
@Override
public void connectComplete(boolean b, String s) {
Log.w("mqtt", s);
}
@Override
public void connectionLost(Throwable throwable) {
}
@Override
public void messageArrived(String topic, MqttMessage mqttMessage) throws Exception {
Log.w("Anjing", mqttMessage.toString());
}
@Override
public void deliveryComplete(IMqttDeliveryToken iMqttDeliveryToken) {
}
});
connect();
}
So what's the problem? Thanks in advance..
EDIT: Of course I can set the mqttAndroidClient
variable in the MqttHandler class as public, but is it safe?