java – Managing reconnections to MQTT server-ThrowExceptions

Exception or error:

I do connect to MQTT server by using MqttAndroidClient:

doReconnect()
{
.....
        mqttAndroidClient.connect(mqttConnectOptions, null,

                new IMqttActionListener()
                {

                    @Override
                    public void onSuccess(IMqttToken asyncActionToken)
                    {
                        Timber.tag(Utils.TIMBER_TAG).v( "onSuccess " + MqttHelper.toString(asyncActionToken));
                        DisconnectedBufferOptions disconnectedBufferOptions = new DisconnectedBufferOptions();
                        disconnectedBufferOptions.setBufferEnabled(false);
                        disconnectedBufferOptions.setBufferSize(100);
                        disconnectedBufferOptions.setPersistBuffer(false);
                        disconnectedBufferOptions.setDeleteOldestMessages(false);
                        mqttAndroidClient.setBufferOpts(disconnectedBufferOptions);
                        subscribeToTopic(top);

                        showMainActivity("Connect OK");

                    }

                    @Override
                    public void onFailure(IMqttToken asyncActionToken, Throwable e) {
                        Timber.tag(Utils.TIMBER_TAG).v( "Failed to connect to: " +uri+" "+e.toString());
                        showMainActivity("Failed while connect "+e.toString());

                        doReconnect()
                    }
                });
....
}

It works fine when server is available. Icase I close port I get OnFailure event which calls doReconnect again. If now I open port I will get two calls onSuccess instead of one and in MQTT server I see two subscribed clients. Looks like previous session is still trying to reconnect. Why I’m getting two calls and how to avoid it?

How to solve:

Leave a Reply

Your email address will not be published. Required fields are marked *