当前位置:   article > 正文

安卓使用Kotlin实现mqtt的连接和主题订阅_kotlin mqtt

kotlin mqtt

目录

需要注意的:


这是记录能用代码的,想知道原理的话,可以自行搜索

二话不说,上代码,拷了就能用

  1. package com.doshare.boardroom.control.comm.mqtt
  2. import android.content.Context
  3. import android.util.Log
  4. import androidx.lifecycle.ViewModelProvider
  5. import com.doshare.boardroom.control.comm.retrofit.BoardRoomControlServiceImpl
  6. import com.doshare.boardroom.control.common.device.AppHelper
  7. import com.doshare.boardroom.control.common.device.DeviceIdUtils
  8. import com.doshare.boardroom.control.view.viewmodel.HomeViewModel
  9. import com.google.gson.Gson
  10. import com.google.gson.internal.LinkedTreeMap
  11. import org.eclipse.paho.android.service.MqttAndroidClient
  12. import org.eclipse.paho.client.mqttv3.*
  13. object MqttClient {
  14. private lateinit var mqttClient: MqttAndroidClient
  15. // TAG
  16. private val TAG = "AndroidMqttClient"
  17. /**
  18. * 创建连接
  19. */
  20. fun connect(context: Context) {
  21. val serverURI = "tcp://172.17.**.202:1883" //mqtt的服务器地址
  22. val username = "ds-mqtt" //用户名
  23. val password = "do***321" //密码
  24. mqttClient = MqttAndroidClient(context, serverURI, "IScreen-"+ DeviceIdUtils.getDeviceId(context))
  25. mqttClient.setCallback(object : MqttCallback {
  26. override fun messageArrived(topic: String?, message: MqttMessage?) {
  27. //这里是对收到mqtt消息进行处理的地方,
  28. Log.d(TAG, "Receive message: ${message.toString()} from topic: $topic")
  29. val messageMap = Gson().fromJson(message.toString(),Map::class.java)as LinkedTreeMap<String, Any>
  30. }
  31. override fun connectionLost(cause: Throwable?) {
  32. Log.d(TAG, "Connection lost ${cause.toString()}")
  33. }
  34. override fun deliveryComplete(token: IMqttDeliveryToken?) {
  35. }
  36. })
  37. // MQTT的连接设置
  38. val options = MqttConnectOptions()
  39. options.userName = username
  40. options.password = password.toCharArray()
  41. try {
  42. mqttClient.connect(options, null, object : IMqttActionListener {
  43. override fun onSuccess(asyncActionToken: IMqttToken?) {
  44. Log.d(TAG, "Connection success")
  45. subscribe("sunblind/user/+/notify") //订阅主题
  46. }
  47. override fun onFailure(asyncActionToken: IMqttToken?, exception: Throwable?) {
  48. Log.d(TAG, "Connection failure")
  49. }
  50. })
  51. } catch (e: MqttException) {
  52. e.printStackTrace()
  53. }
  54. }
  55. /**
  56. * 订阅主题
  57. */
  58. fun subscribe(topic: String, qos: Int = 1) {
  59. try {
  60. mqttClient.subscribe(topic, qos, null, object : IMqttActionListener {
  61. override fun onSuccess(asyncActionToken: IMqttToken?) {
  62. Log.d(TAG, "Subscribed to $topic")
  63. }
  64. override fun onFailure(asyncActionToken: IMqttToken?, exception: Throwable?) {
  65. Log.d(TAG, "Failed to subscribe $topic")
  66. }
  67. })
  68. } catch (e: MqttException) {
  69. e.printStackTrace()
  70. }
  71. }
  72. /**
  73. * 取消订阅
  74. */
  75. fun unsubscribe(topic: String) {
  76. try {
  77. mqttClient.unsubscribe(topic, null, object : IMqttActionListener {
  78. override fun onSuccess(asyncActionToken: IMqttToken?) {
  79. Log.d(TAG, "Unsubscribed to $topic")
  80. }
  81. override fun onFailure(asyncActionToken: IMqttToken?, exception: Throwable?) {
  82. Log.d(TAG, "Failed to unsubscribe $topic")
  83. }
  84. })
  85. } catch (e: MqttException) {
  86. e.printStackTrace()
  87. }
  88. }
  89. /**
  90. * 发布消息
  91. */
  92. fun publish(topic: String, msg: String, qos: Int = 1, retained: Boolean = false) {
  93. try {
  94. val message = MqttMessage()
  95. message.payload = msg.toByteArray()
  96. message.qos = qos
  97. message.isRetained = retained
  98. mqttClient.publish(topic, message, null, object : IMqttActionListener {
  99. override fun onSuccess(asyncActionToken: IMqttToken?) {
  100. Log.d(TAG, "$msg published to $topic")
  101. }
  102. override fun onFailure(asyncActionToken: IMqttToken?, exception: Throwable?) {
  103. Log.d(TAG, "Failed to publish $msg to $topic")
  104. }
  105. })
  106. } catch (e: Exception) {
  107. e.printStackTrace()
  108. }
  109. }
  110. /**
  111. * 取消连接
  112. */
  113. fun disconnect() {
  114. try {
  115. mqttClient.disconnect(null, object : IMqttActionListener {
  116. override fun onSuccess(asyncActionToken: IMqttToken?) {
  117. Log.d(TAG, "Disconnected")
  118. }
  119. override fun onFailure(asyncActionToken: IMqttToken?, exception: Throwable?) {
  120. Log.d(TAG, "Failed to disconnect")
  121. }
  122. })
  123. } catch (e: MqttException) {
  124. e.printStackTrace()
  125. }
  126. }
  127. }

需要注意的:

1.connect方法中serverURI //mqtt的服务器地址,username  //用户名,password  //密码这三个数据换成自己的
2.  mqttClient.connect中订阅的主题换成自己的

3.上面import了好多的无用包,直接删掉

4.改包名

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/很楠不爱3/article/detail/386485
推荐阅读
相关标签
  

闽ICP备14008679号