android mqtt demo

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);
        }
    }
}
相关推荐
平头哥技术团队1 天前
Day 10 | 工欲善其事:VS Code 配置与项目归档
android·开发语言·前端·javascript·html·交互
冬木家居1 天前
40㎡客厅变形记,小家住出大自由[特殊字符]
android·经验分享·笔记·智能家居·微信公众平台
AFinalStone1 天前
Android 7系统无障碍服务(六)输入事件拦截与 TouchExplorer
android·无障碍服务
天空之城--1 天前
MT管理器Android逆向工程完全指南:从入门到实战
android
Anhty1 天前
2026九月最新变声器测评:iOS安卓双端适配,低延迟运行更稳定
android·人工智能·功能测试·ios·智能手机
渡我白衣1 天前
并查集:基础认识与模拟实现
android·java·javascript·数据结构·c++·算法·并查集
Android-Flutter1 天前
flutter GetX 详解
android·flutter
MyFreeIT1 天前
Android Manual
android
hai_android1 天前
AIDL 实现 IPC 进程间通信
android·android studio
AFinalStone1 天前
Android 7系统无障碍服务(五)AccessibilityNodeInfo 的构建与查询
android·无障碍服务