Paho's MQTT client disconnects after the device locks

限于喜欢 提交于 2019-12-31 05:03:45

问题


I'm currently working on a small "Panic Button" app supposed to operate in a medical facility. As one of the project's assumptions is to be Internet-independent, I've decided to go for MQTT with a server set up in the local WLAN.

I've implemented the Paho Android Service and it works pretty good. Up to a certain point. Once I lock the device and turn off the sreen, exactly after one minute the client gets disconnected. As I've set MQTT options to KeepAlive interval of 30s, this must be caused by Android itself, probably going into its lock-sleep. I'm obtaining the same results on couple of different smartphones, so it is probably also not user settings - related.

I'd rather avoid setting up an auto-reconnect procedure in

 public class ServerCallback implements MqttCallback
{
    public void connectionLost(Throwable cause) { 
    ...
    }
}

Because I want to use this method to prompt an error dialog once connection is lost due to less predictable reasons.

If so, what options do I have to prevent this disconnection?

EDIT:

Additional observation of mine is that as long as the device is plugged in and charging, disconnection does not occur.


回答1:


After googling around I think I found the reason:

The Paho MQTT client uses a TimerTask to schedule the keepalive ping. A TimerTask will stop when the phone goes to sleep, and is therefore a poor choice here... The implementation for the keepalive ping can be found in the class TimerPingSender which is derived from the MqttPingSender class.

In order to get timed events when the phone is sleeping, it must be triggered by the AlarmManager. The best solution to the problem I found was to make an alternative class derived from the MqttPingSender class. Before I started writing such a class myself, I googled and found someone who had already done it on GitHub.

It can be found here: https://github.com/Suxsem/Domo-Android/blob/master/app/src/main/java/com/suxsem/domo/MqttPingSender.java

I also had to add an alternative constructor to MqttClient:

public MqttClient(String serverURI, String clientId, MqttClientPersistence persistence, MqttPingSender pingSender) throws MqttException {
    aClient = new MqttAsyncClient(serverURI, clientId, persistence, pingSender);
}

and where I instantiate the MqttClient (in my Service) I do this:

MqttPingSender pingSender = new MqttPingSenderAlarm(this);
mqClient = new MqttClient("tcp://<IP>:<PORT>", "MyTestServiceID", new MemoryPersistence(), pingSender);

Until now this seems to work flawlessly, but I've only tested it 20-30 minutes.



来源:https://stackoverflow.com/questions/37699240/pahos-mqtt-client-disconnects-after-the-device-locks

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!