MQTTService.java
package com.example.demo01;
import android.util.Log;
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.IMqttMessageListener;
import org.eclipse.paho.client.mqttv3.MqttMessage;
public class MQTTService {
private static final String TAG = "MQTTService";
private static final String BROKER_URL = "tcp://192.168.2.44:1883"; // Example public broker
private static final String CLIENT_ID = "AndroidClient";
private static final String TOPIC = "test/topic";
private MqttClient mqttClient;
private MqttConnectOptions connectOptions;
public MQTTService() throws MqttException {
// Create an MQTT client and connect to the broker
mqttClient = new MqttClient(BROKER_URL, CLIENT_ID, null);
connectOptions = new MqttConnectOptions();
connectOptions.setCleanSession(true);
// Connect to the MQTT broker
mqttClient.connect(connectOptions);
Log.d(TAG, "Connected to MQTT Broker");
// Subscribe to a topic
mqttClient.subscribe(TOPIC, new IMqttMessageListener() {
@Override
public void messageArrived(String topic, MqttMessage message) throws Exception {
Log.d(TAG, "Message received: " + new String(message.getPayload()));
}
});
}
public void publishMessage(String message) throws MqttException {
MqttMessage mqttMessage = new MqttMessage();
mqttMessage.setPayload(message.getBytes());
mqttClient.publish(TOPIC, mqttMessage);
Log.d(TAG, "Message published: " + message);
}
public void disconnect() throws MqttException {
mqttClient.disconnect();
Log.d(TAG, "Disconnected from MQTT Broker");
}
}
Activity:
package com.example.demo01;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import androidx.activity.EdgeToEdge;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.graphics.Insets;
import androidx.core.view.ViewCompat;
import androidx.core.view.WindowInsetsCompat;
import org.eclipse.paho.client.mqttv3.MqttException;
public class MainActivity extends AppCompatActivity implements View.OnClickListener {
private MQTTService mqttService;
Button buttonTest;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
EdgeToEdge.enable(this);
setContentView(R.layout.activity_main);
try {
mqttService = new MQTTService();
} catch (MqttException e) {
throw new RuntimeException(e);
}
buttonTest = findViewById(R.id.buttonMqttTest);
buttonTest.setOnClickListener(this);
Log.d("ARIC", "########");
ViewCompat.setOnApplyWindowInsetsListener(findViewById(R.id.main), (v, insets) -> {
Insets systemBars = insets.getInsets(WindowInsetsCompat.Type.systemBars());
v.setPadding(systemBars.left, systemBars.top, systemBars.right, systemBars.bottom);
return insets;
});
}
@Override
public void onClick(View v) {
try {
mqttService.publishMessage("Hello, MQTT!");
} catch (MqttException e) {
throw new RuntimeException(e);
}
}
}