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);
        }
    }
}
相关推荐
麻辣炖土豆儿3 小时前
Android BottomNavigationView不加icon使text垂直居中,完美解决。
android
听我一言4 小时前
Qt for android : 简单实现弹窗创建文件,并使用JNI进行读写实例
android·开发语言·qt
小兵小卒4 小时前
ElectronSharp,.Net跨平台的多一种选择
android·macos·c#·.net·wpf
alexhilton4 小时前
Compose多平台 (CMP) 开发的四个实用技巧
android·kotlin·android jetpack
氤氲息6 小时前
Android fragment的写
android
ytuglt7 小时前
Mac M1处理器uiautomatorviewer 使用
android·macos
柯南二号7 小时前
Android JecPack组件之LifeCycles 使用详解
android·jetpack·lifecycles
万亿少女的梦1688 小时前
基于php求职招聘系统设计
android·php·求职招聘
xvch8 小时前
Kotlin 2.1.0 入门教程(一)
android·kotlin