使用android客户的链接mqtt服务,发现一个非常不错的mqtt-client-Android-Kotlin 项目

1,172 阅读1分钟

1,关于mqtt-android


项目代码:

github.com/emqx/MQTT-C… 

下面的: mqtt-client-Android-Kotlin 项目

  • 编程语言: Kotlin
  • 开发工具: Android Studio
  • 使用eclipse的paho框架版本3库

在android上面使用eclipse的paho框架版本3。

implementation 'org.eclipse.paho:org.eclipse.paho.client.mqttv3:1.2.5'
implementation 'org.eclipse.paho:org.eclipse.paho.android.service:1.1.1'

拆分的项目代码放到:

gitee.com/study-demo-…

2,项目可以支持使用webscoket连接mqtt


带一个 界面,可以配置好 mqtt 连接地址和端口。

截图_2023-02-20_23-18-03.png

这边本地开启 8883 的websocket 端口,提供给mqtt 使用。 可以订阅 topic,发送消息后 通过message 接受到消息。


class Connection(
    private val context: Context,
    var host: String,
    var port: Int,
    var clientId: String,
    var username: String,
    var password: String,
    private val tls: Boolean
) {
    fun getMqttAndroidClient(context: Context?): MqttAndroidClient {
        val uri: String = if (tls) {
            "ssl://$host:$port"
        } else {// 默认协议修改成了 websocket.
            "ws://$host:$port"
        }
        return MqttAndroidClient(context, uri, clientId)
    }

    val mqttConnectOptions: MqttConnectOptions
        get() {
            val options = MqttConnectOptions()
            // clean session = true .
            // 设置关闭的时候清理session否则连接判断不准确。
            options.isCleanSession = true

            if (tls) {
                try {
                    options.socketFactory =
                        SSLUtils.getSingleSocketFactory(context.resources.openRawResource(R.raw.cacert))
                } catch (e: Exception) {
                    e.printStackTrace()
                }
            }
            if (username.isNotEmpty()) {
                options.userName = username
            }
            if (password.isNotEmpty()) {
                options.password = password.toCharArray()
            }
            return options
        }
}

3,总结


这个 demo 确实非常的简单,也很好用,可以直接跑起来。 上面还有很多其他的demo,以后慢慢研究。研究mqtt协议,主要是订阅消息。