How to force an immediate connection attempt on Android?

"I am using hivemq-mqtt-client:1.3.12 on Android (for a turn-based game.) When the OS blocks the connection (e.g., background restrictions), the client enters DISCONNECTED_RECONNECT.

My issue is that when the user brings the app to the foreground they expect an immediate connection. However:

  • Calling disconnect() throws a MqttClientStateException (not connected).

  • The internal backoff timer doesn’t seem to reset upon calling connect() (or disconnect()) manually.

Is there a supported way to “interrupt” a scheduled reconnection task from outside the DisconnectedListener?

My current choices seem to be either:

  1. Use a super-short maxDelay

  2. Build a new client every time the app is foregrounded and the existing client’s next scheduled connection attempt is too far out

Thanks,

–Eric House

Hello Eric,

thanks for the detailed description of your setup and for using the HiveMQ MQTT Client on Android . You are right in your observations: There is no supported API to externally cancel or “interrupt” an already scheduled automatic reconnect attempt once the client is in DISCONNECTEDRECONNECT. Calling disconnect() in that state throws MqttClientStateException because the client is already disconnected, and connect() does not reset the internal backoff timer.

The only supported way to influence the reconnect timing is inside the DisconnectedListener using the MqttClientDisconnectedContext:

client.toAsync().addDisconnectedListener(context → {
context.getReconnector()
.reconnect(true)
.delay(0, TimeUnit.MILLISECONDS);
});

That is the intended mechanism for overriding the current backoff delay (e.g., when your app returns to foreground).

If you need foreground-triggered immediate reconnects outside that listener, the supported approaches are:

  • Disable automatic reconnect and manage reconnects manually, or
  • Create a new client instance (which resets reconnect state)

There is no external “reset backoff” API.

Regards,
Sheetal from HiveMQ Support