How to connect with MQTT Broker and publish a MQTT Message and Subscribe in Android Studio Java App
Автор: Coffee Programmer
Загружено: 2023-02-05
Просмотров: 22347
Описание:
Can you help me to buy a coffee:
https://www.buymeacoffee.com/coffeepr... Download Project : https://drive.google.com/drive/folder...
Github: https://github.com/ashenishanka/MQTT-...
dependencies {
implementation 'org.eclipse.paho:org.eclipse.paho.client.mqttv3:1.2.0'
}
import org.eclipse.paho.client.mqttv3.MqttClient;
import org.eclipse.paho.client.mqttv3.MqttConnectOptions;
import org.eclipse.paho.client.mqttv3.MqttException;
import org.eclipse.paho.client.mqttv3.MqttMessage;
import org.eclipse.paho.client.mqttv3.persist.MemoryPersistence;
public class MqttHandler {
private MqttClient client;
public void connect(String brokerUrl, String clientId) {
try {
// Set up the persistence layer
MemoryPersistence persistence = new MemoryPersistence();
// Initialize the MQTT client
client = new MqttClient(brokerUrl, clientId, persistence);
// Set up the connection options
MqttConnectOptions connectOptions = new MqttConnectOptions();
connectOptions.setCleanSession(true);
// Connect to the broker
client.connect(connectOptions);
} catch (MqttException e) {
e.printStackTrace();
}
}
public void disconnect() {
try {
client.disconnect();
} catch (MqttException e) {
e.printStackTrace();
}
}
public void publish(String topic, String message) {
try {
MqttMessage mqttMessage = new MqttMessage(message.getBytes());
client.publish(topic, mqttMessage);
} catch (MqttException e) {
e.printStackTrace();
}
}
public void subscribe(String topic) {
try {
client.subscribe(topic);
} catch (MqttException e) {
e.printStackTrace();
}
}
}
Повторяем попытку...
Доступные форматы для скачивания:
Скачать видео
-
Информация по загрузке: