MQTT 사용하기
2021. 10. 13. 14:40ㆍAndroid/MQTT
Step 1. MQTT 라이브러리 Dependency
implementation 'org.eclipse.paho:org.eclipse.paho.client.mqttv3:1.2.5'
implementation 'org.eclipse.paho:org.eclipse.paho.android.service:1.1.1'
Step 2. Android 권한 설정 및 MQTT 서비스 등록
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.mqtt">
<uses-permission android:name="android.permission.WAKE_LOCK" />
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<application
....
<service android:name="org.eclipse.paho.android.service.MqttService" />
</application>
</manifest>
Step 2. MQTT 메세지 서버 전송
var mqttclient = MqttClient("tcp://192.168.0.252:1883", MqttClient.generateClientId(), null)
mqttclient.connect()
mqttclient.publish(TOPIC, MqttMessage("ssss".toByteArray()))
Step 3. MQTT 서버 반환 메세지 받기
mqttclient.subscribe(TOPIC)
mqttclient.setCallback(object : MqttCallback {
override fun connectionLost(cause: Throwable?) {
}
override fun messageArrived(topic: String?, message: MqttMessage?) {
Log.i(TAG, "topic = $topic, message = $message")
}
override fun deliveryComplete(token: IMqttDeliveryToken?) {
}
})
Git
'Android > MQTT' 카테고리의 다른 글
MQTT Option(Retain,CleanSession,LWT) (0) | 2021.10.22 |
---|---|
MQTT Option(Qos) (0) | 2021.10.22 |
Mosquitto 설치 및 테스트 (0) | 2021.10.13 |