Java – Android – Once the network connection changes (mobile data is disabled and enabled again), the Paho MQTT client does not receive messages

Android – Once the network connection changes (mobile data is disabled and enabled again), the Paho MQTT client does not receive messages… here is a solution to the problem.

Android – Once the network connection changes (mobile data is disabled and enabled again), the Paho MQTT client does not receive messages

I’m using Mosquitto MQTT and the paho API to receive push messages on my Android device. But as soon as the network connection changes, it stops receiving messages. Here are the steps to reproduce the issue using a simple test case:

1) Create a simple activity.

2) Connect to the mosquitto test server (test.mosquitto.org:1883) via the paho API on Activity StartUp.

3) Subscribe to some topics.

4) Post some messages to the topic.

Result: The MQTT Client receives all messages published to the topic. Now

5) Disable internet connection (mobile data) on mobile devices

6) Post some news to the topic.

7) Reconnect to the Internet.

Result: The client does not receive any messages published after the Internet connection is disabled.

Since KeepAliveInterval has remained high (30 minutes), it should receive all messages after reconnecting to the internet.

Same use case (

same code) for simple java project (non-android) I disabled internet on my laptop to run that use case.

Any idea why it won’t work on Android devices??? Am I missing something?

Note:

1) Use mqtt-client-0.4.1

2) Android Target API level 11

3) Do not put the device into sleep mode during the test.

4) No calls are made in the connectionLost callback, and all 4 threads of the mqtt callback are running throughout the test case, i.e. the connection to the mosquitto server is intact.

Solution

Java client libraries are governed to some extent by the underlying network APIs. When publish is called, it writes MQTT packets to the socket. If that write fails, the calling connection is lost, and if the write is valid, the client library continues. The difference in behavior that you see is because the network library behaves differently in these cases.

MQTT keepalive intervals are designed to help solve this problem. In some cases, a TCP connection may appear to be active, but is not. This can especially happen on mobile or satellite-connected devices – you can’t expect the network APIs to be exactly the same in all cases. Keepalive sends a ping packet to the server and expects a response – if it is not received, the session is considered closed.

If you set the keepalive interval to 10 seconds, the connection should be recognized as disconnected within 15 to 20 seconds.

Related Problems and Solutions