Mqtt断开连接disconnect报错原因

2019年12月11日 2点热度 0条评论 来源: hacker_crazy

最近在用mqtt做及时通信,mqtt服务本身是放在本地的service服务里面运行,在应用关闭的时候,mqtt服务也要断开连接,不然会继续占用服务器的cpu,增加服务器负担。所以,在service的onDestroy中,需要调用MqttAndroidClient.disconnect()方法,但是会出现如下报错Log:

Service org.eclipse.paho.android.service.MqttService has leaked IntentReceiver org.eclipse.paho.android.service.AlarmPingSender$AlarmReceiver@29e9a4b8 that was originally registered here. Are you missing a call to unregisterReceiver()?
    android.app.IntentReceiverLeaked: Service org.eclipse.paho.android.service.MqttService has leaked IntentReceiver org.eclipse.paho.android.service.AlarmPingSender$AlarmReceiver@29e9a4b8 that was originally registered here. Are you missing a call to unregisterReceiver()?
        at android.app.LoadedApk$ReceiverDispatcher.<init>(LoadedApk.java:903)
        at android.app.LoadedApk.getReceiverDispatcher(LoadedApk.java:704)
        at android.app.ContextImpl.registerReceiverInternal(ContextImpl.java:1650)
        at android.app.ContextImpl.registerReceiver(ContextImpl.java:1630)
        at android.app.ContextImpl.registerReceiver(ContextImpl.java:1624)
        at android.content.ContextWrapper.registerReceiver(ContextWrapper.java:489)
        at org.eclipse.paho.android.service.AlarmPingSender.start(AlarmPingSender.java:74)
        at org.eclipse.paho.client.mqttv3.internal.ClientState.connected(ClientState.java:1149)
        at org.eclipse.paho.client.mqttv3.internal.ClientState.notifyReceivedAck(ClientState.java:985)
        at org.eclipse.paho.client.mqttv3.internal.CommsReceiver.run(CommsReceiver.java:145)
        at java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:422)
        at java.util.concurrent.FutureTask.run(FutureTask.java:237)
        at java.util.concurrent.ScheduledThreadPoolExecutor$ScheduledFutureTask.access$201(ScheduledThreadPoolExecutor.java:152)
        at java.util.concurrent.ScheduledThreadPoolExecutor$ScheduledFutureTask.run(ScheduledThreadPoolExecutor.java:265)
        at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1112)
        at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:587)
        at java.lang.Thread.run(Thread.java:818)

这是因为在断开disconnect的时候,需要解注册mqttAndroidClient的广播;因为mqttAndroidClient本身就是一个广播。

解注册广播需要调用unregisterResources方法。

但是广播本身就是系统的底层通信,属于异步操作,然后接着调用disconnect就会导致广播还没有解注册就进行diconnect,

会出现上述报错。

 

测试方法很简单,在两者之间增加一个Thread.sleep(50);

做一个50ms的线程阻塞等待,就可以避免该情况的出现。

如下图:

    原文作者:hacker_crazy
    原文地址: https://blog.csdn.net/hacker_crazy/article/details/103489861
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系管理员进行删除。