android kotlin连接mqtt断开连接时使用disconnect()函数报错解决

MQTT断开连接disconnect()函数报错解决

前言:这个问题是笔者在一次学习开发时遇到的问题,也是查阅了很多资料和文章后试出来的解决方法。笔者并不知道具体问题原因。mqtt的连接及使用方法也是参照官方的文章,只有disconnect()函数报错导致程序崩溃。

  • 开发语言:kotlin
    首先上能够正常运行并且实现功能的代码
/***
     * 断开连接
     */
    fun disconnect() {
        try {
            mClient?.unregisterResources();
            mClient?.disconnect(null, object : IMqttActionListener {
                override fun onSuccess(asyncActionToken: IMqttToken?) {
                    Log.d(TAG, "断开连接")
                }
                override fun onFailure(asyncActionToken: IMqttToken?, exception: Throwable?) {
                    Log.d(TAG, "断开失败")
                }
            })
            mClient = null;
            CONNECT_FLAG = false
        } catch (e: MqttException) {
            e.printStackTrace()
            Log.d(TAG, "断开连接--错误")
        }
    }

其中CONNECT_FLAG 为是否连接的标志位,不用关心。
而根据官方写的原代码,会在调用时报错
android kotlin连接mqtt断开连接时使用disconnect()函数报错解决_第1张图片
如果只在官方代码上只加mClient = null会报错:
android kotlin连接mqtt断开连接时使用disconnect()函数报错解决_第2张图片
而如果只加上 mClient?.unregisterResources()会报错:
android kotlin连接mqtt断开连接时使用disconnect()函数报错解决_第3张图片
所以需要两行代码一起加上就能够正常运行了。

你可能感兴趣的:(#,Android天天踩坑,android,kotlin,mqtt)