spike32
spike32

Reputation: 45

MqttAndroidClient not able to connect to mosquitto

I have a mosquitto broker running on my computer with mosquitto -v and I'm trying to connect to it from my android app. What I am doing is

public void connect() {
        mqttAndroidClient = new MqttAndroidClient(context, "mqtt://192.168.1.198:1883", clientId);
        mqttAndroidClient.setCallback(callback);

        mqttConnectOptions = new MqttConnectOptions();
        mqttConnectOptions.setAutomaticReconnect(true);
        mqttConnectOptions.setCleanSession(false);

        mqttAndroidClient.connect(mqttConnectOptions, context, new IMqttActionListener() {
                @Override
                public void onSuccess(IMqttToken asyncActionToken) {
                    DisconnectedBufferOptions disconnectedBufferOptions = new DisconnectedBufferOptions();
                    disconnectedBufferOptions.setBufferEnabled(true);
                    disconnectedBufferOptions.setBufferSize(100);
                    disconnectedBufferOptions.setPersistBuffer(false);
                    disconnectedBufferOptions.setDeleteOldestMessages(false);
                    mqttAndroidClient.setBufferOpts(disconnectedBufferOptions);
                    Log.i(LOG_TAG, "Connected to the broker");
                }

                @Override
                public void onFailure(IMqttToken asyncActionToken, Throwable exception) {
                    Log.e(LOG_TAG, "Not able to connect to the broker");
                }
        });

        while(!mqttAndroidClient.isConnected()) {}
        try {
            mqttAndroidClient.subscribe("notify/new", 0);
        } catch (MqttException ex) {
            System.err.println("Exception whilst subscribing");
            ex.printStackTrace();
        }
}

But it never connects, because I don't see the "Connected to the broker" message and it gets in stuck in the while loop. What am I doing wrong?

Upvotes: 0

Views: 386

Answers (1)

hardillb
hardillb

Reputation: 59608

As covered in the comments, the tight while loop checking if the client is connected is redundant as there is already a callback onSuccess() that can be used for that test.

The call to subscribe() should be moved into the callback.

The best way to handle subscribing to topics after the client is connected is to gate the call to subscribe() in an if block that checks the connected status. If that test fails add the topic to a global array, and call connect() again. The subscribe() in the onSuccess() callback should use the version that takes an array of topics

Upvotes: 1

Related Questions