paho.mqtt.android
paho.mqtt.android copied to clipboard
Mqtt never return callback connection lost when broker server disconnect the network(wifi).
I integrated an MQTT broker into my app, establishing a connection between the Android device and the Mosquitto broker on a computer server. However, in my scenario, when I disconnect the Wi-Fi on the server, the broker connection doesn't trigger the callback method to indicate connection loss on Android.
// for Mqtt dependencies implementation 'androidx.legacy:legacy-support-v4:1.0.0' implementation 'com.github.hannesa2:paho.mqtt.android:4.2'
protected void mqttBrokerStartConnect(String deviceId) {
IMqttToken token;
String brokerIP = AppSharePreference.getMQTTBrokerIP(getBaseContext());
String uri = "tcp://" + brokerIP;
//String clientId = MqttClient.generateClientId();
String clientId = "MyClientId";
mqttClient = new MqttAndroidClient(getApplicationContext(), uri, clientId, Ack.AUTO_ACK);
mqttClient.setTraceEnabled(true);
// Work in the UI thread
MqttConnectOptions connectOptions = new MqttConnectOptions();
connectOptions.setUserName("username");
connectOptions.setPassword("password".toCharArray());
connectOptions.setCleanSession(false);
String message = payLoadConnection(deviceId);
connectOptions.setWill(CommonConstants.willDisconnectTopic, message.getBytes(), 0, false);
connectOptions.setAutomaticReconnect(true);
connectOptions.setConnectionTimeout(10); // Set connection timeout to 10 seconds
connectOptions.setKeepAliveInterval(60);
token = mqttClient.connect(connectOptions);
token.setActionCallback(this);
mqttClient.setCallback(this);
mqttClient.setTraceCallback(this);
}
@Override
public void connectionLost(Throwable cause) {
EventBus.getDefault().post(new ResultEvent.MqttConnectionStatusEvent(getBaseContext(), false));
// mqttClient.connect();
}