Android Studio实现MQTT数据收发及数据处理

前言

在前面已经通过阿里云服务器搭建了MQTT平台,这里为大家分享MQTT在安卓开发上的使用

环境搭建

1、创建简单工程
在这里插入图片描述
2、主要修改一下三个文件
在这里插入图片描述
(1)AndroidManifest.xml
添加权限

<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
<!-- Permissions the Application Requires -->
<uses-permission android:name="android.permission.WAKE_LOCK" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.READ_PHONE_STATE" />

添加服务(在application里)

<service android:name="org.eclipse.paho.android.service.MqttService"></service>

(2)build.gradle
添加依赖

dependencies{
...............

    //mqtt
    implementation 'org.eclipse.paho:org.eclipse.paho.client.mqttv3:1.1.0'
    implementation 'org.eclipse.paho:org.eclipse.paho.android.service:1.1.1'
    implementation 'androidx.legacy:legacy-support-v4:1.0.0'

}

(3)gradle.properties
添加支持

android.enableJetifier=true

布局设计

在这里插入图片描述
直接贴代码

<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity">

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:orientation="vertical">

        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="40dp"
            android:layout_marginLeft="20dp"
            android:layout_marginRight="20dp"
            android:orientation="horizontal">

            <Switch
                android:id="@+id/mqtt_switch"
                android:layout_width="100dp"
                android:layout_height="match_parent"
                android:text="Switch" />

            <androidx.constraintlayout.widget.ConstraintLayout
                android:layout_width="30dp"
                android:layout_height="match_parent">

            </androidx.constraintlayout.widget.ConstraintLayout>

            <Button
                android:id="@+id/mqtt_button"
                android:layout_width="100dp"
                android:layout_height="match_parent"
                android:text="点击" />

            <androidx.constraintlayout.widget.ConstraintLayout
                android:layout_width="30dp"
                android:layout_height="match_parent">

            </androidx.constraintlayout.widget.ConstraintLayout>

            <Button
                android:id="@+id/clean_button"
                android:layout_width="100dp"
                android:layout_height="wrap_content"
                android:layout_weight="1"
                android:text="清空" />

        </LinearLayout>

        <TextView
            android:id="@+id/mqttMessage"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:paddingLeft="30dp"
            android:paddingTop="20dp"
            android:paddingEnd="50dp"
            android:paddingRight="30dp"
            android:text="TextView"
            android:textSize="30px" />
    </LinearLayout>

</androidx.constraintlayout.widget.ConstraintLayout>

MQTT相关程序

定义各种变量

public final String TAG = "MQTT";
private MqttAndroidClient mqttAndroidClient;
private MqttConnectOptions mMqttConnectOptions;
public String MQTT_HOST = "tcp://xxx.xxx.xxx.xxx:1883";//服务器地址
public String MQTT_UserName = "admin";              // 用户名
public String MQTT_PassWord = "admin";             // 密码
public int MQTT_ConnectionTimeout = 10;             // 设置超时时间,单位:秒
public int KeepAliveIntervalTime = 20;              // 设置心跳包发送间隔,单位:秒
public boolean CleanSession = true;                 // 设置是否清除缓存
public String Subscribe_Topic = "androidTopic";      // 客户端订阅主题
public String EndWillMsgPublish_Topic = "EndWillMsg";// 遗嘱发布主题
public static String RESPONSE_TOPIC = "message_arrived";//响应主题

public String CLIENTID = "test";
private Handler MQTThandler;

初始化函数

// 初始化
public void init(Context context, Handler MQTThandlerS) {
    MQTThandler = MQTThandlerS;
    String serverURI = MQTT_HOST; //服务器地址
    mqttAndroidClient = new MqttAndroidClient(context, serverURI, CLIENTID);
    mqttAndroidClient.setCallback(mqttCallback); //设置监听订阅消息的回调
    mMqttConnectOptions = new MqttConnectOptions();
    mMqttConnectOptions.setCleanSession(CleanSession); //设置是否清除缓存
    mMqttConnectOptions.setConnectionTimeout(MQTT_ConnectionTimeout); //设置超时时间,单位:秒
    mMqttConnectOptions.setKeepAliveInterval(KeepAliveIntervalTime); //设置心跳包发送间隔,单位:秒
    mMqttConnectOptions.setUserName(MQTT_UserName); //设置用户名
    mMqttConnectOptions.setPassword(MQTT_PassWord.toCharArray()); //设置密码

    // last will message
    boolean doConnect = true;
    String message = "{\"terminal_uid\":\"" + CLIENTID + "\",\"msg\":\"Client offline\"}";
    // 最后的遗嘱
    try {
        mMqttConnectOptions.setWill(EndWillMsgPublish_Topic, message.getBytes(), 2, false);
    } catch (Exception e) {
        Log.e(TAG, "Exception Occured", e);
        doConnect = false;
    }
    if (doConnect) {
        doClientConnection();
    }
}

连接MQTT

// 连接MQTT服务器
private void doClientConnection() {
    if (!mqttAndroidClient.isConnected()) {
        try {
            mqttAndroidClient.connect(mMqttConnectOptions, null, new IMqttActionListener() {
                @Override
                public void onSuccess(IMqttToken asyncActionToken) {
                    MQTT_Subscribe(Subscribe_Topic);
                    MQTT_Subscribe("androidTopic2");
                    System.out.println("连接mqtt服务器成功");

                }

                @Override
                public void onFailure(IMqttToken asyncActionToken, Throwable exception) {
                    System.out.println("连接mqtt服务器失败");
                }
            });
        } catch (MqttException e) {
            e.printStackTrace();
        }
    }
}

订阅主题及数据处理

// 订阅主题的回调
private MqttCallback mqttCallback = new MqttCallback() {
    @Override
    public void messageArrived(String topic, MqttMessage message) throws Exception {
        Log.e(TAG, "收到消息MQTT: " + topic + " 发来的消息 :" + new String(message.getPayload()));
    }

    @Override
    public void deliveryComplete(IMqttDeliveryToken arg0) {

    }

    @Override
    public void connectionLost(Throwable arg0) {
        Log.e(TAG, "MQTT 服务器连接断开 ");
        doClientConnection();//连接断开,重连
    }
};

// 订阅该主题
private void MQTT_Subscribe(String Publish_Topic) {
    Boolean retained = false;// 是否在服务器保留断开连接后的最后一条消息
    try {
        mqttAndroidClient.subscribe(Publish_Topic, 0, null, new IMqttActionListener() {
            //订阅成功
            @Override
            public void onSuccess(IMqttToken asyncActionToken) {
                System.out.println("订阅成功");
            }

            //订阅失败
            @Override
            public void onFailure(IMqttToken asyncActionToken, Throwable exception) {
                System.out.println("订阅失败" + exception);
            }
        });

        //接收返回的信息(对返回的内容进行相关的操作)
        mqttAndroidClient.subscribe(Publish_Topic, 0, new IMqttMessageListener() {
            @Override
            public void messageArrived(String topic, MqttMessage message) throws Exception {
                Message msg = new Message();
                MyMqttMessage myMqttMessage = new MyMqttMessage(topic, message.toString());
                msg.obj = myMqttMessage;
                MQTThandler.sendMessage(msg);

                System.out.println("主题:" + topic);
                System.out.println("消息:" + message);
            }
        });

    } catch (MqttException e) {
        e.printStackTrace();
    }
}

取消订阅

// 取消订阅
public void MQTT_UnSubscribe(String Publish_Topic) {
    Boolean retained = false;// 是否在服务器保留断开连接后的最后一条消息
    try {
        mqttAndroidClient.unsubscribe(Publish_Topic);
    } catch (MqttException e) {
        e.printStackTrace();
    }
}

消息发布

// 向相关主题发布消息
public void MQTT_Publish(String Publish_Topic, Integer qos, String message) {
    Boolean retained = false;// 是否在服务器保留断开连接后的最后一条消息
    try {
        //参数分别为:主题、消息的字节数组、服务质量、是否在服务器保留断开连接后的最后一条消息
        mqttAndroidClient.publish(Publish_Topic, message.getBytes(), qos, retained.booleanValue());
    } catch (MqttException e) {
        e.printStackTrace();
    }
}

主函数调用(主要程序)

MyMqtt myMqtt = new MyMqtt();
myMqtt.init(context, MQTTHandler);

button.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View view) {
        //发送消息
        myMqtt.MQTT_Publish("androidTopic2", 0, "按钮点击了");
    }
});

效果图

点击按钮
在这里插入图片描述
切换开关
在这里插入图片描述
接收到该主题下的内容
在这里插入图片描述

完整工程代码

https://download.csdn.net/download/qq_46079439/85174550

  • 28
    点赞
  • 127
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 13
    评论
### 回答1: 在Android Studio中,要实现MQTT数据收发,可以按照以下步骤进行: 1. 添加MQTT依赖库:在app模块的build.gradle文件中,添加以下依赖: ``` dependencies { ... implementation 'org.eclipse.paho:org.eclipse.paho.client.mqttv3:1.2.5' } ``` 2. 创建MQTT客户端:在需要使用MQTT的页面或类中,创建MQTT客户端对象,如下所示: ``` import org.eclipse.paho.client.mqttv3.MqttClient; import org.eclipse.paho.client.mqttv3.MqttException; import org.eclipse.paho.client.mqttv3.MqttMessage; import org.eclipse.paho.client.mqttv3.persist.MemoryPersistence; public class MyMqttClient { private MqttClient mqttClient; public MyMqttClient(String broker, String clientId) { try { mqttClient = new MqttClient(broker, clientId, new MemoryPersistence()); } catch (MqttException e) { e.printStackTrace(); } } } ``` 3. 连接MQTT服务器:在创建MQTT客户端后,可以通过以下方法连接到MQTT服务器: ``` public void connect() { try { mqttClient.connect(); } catch (MqttException e) { e.printStackTrace(); } } ``` 4. 发布消息:可以通过以下方法向MQTT主题发布消息: ``` public void publish(String topic, String message) { try { MqttMessage mqttMessage = new MqttMessage(message.getBytes()); mqttClient.publish(topic, mqttMessage); } catch (MqttException e) { e.printStackTrace(); } } ``` 5. 订阅主题:可以使用以下方法订阅MQTT主题,接收消息: ``` public void subscribe(String topic) { try { mqttClient.subscribe(topic, (topic, message) -> { String receivedMessage = new String(message.getPayload()); // 处理接收到的消息 }); } catch (MqttException e) { e.printStackTrace(); } } ``` 以上就是使用Android Studio进行MQTT收发数据的一般流程。需要注意的是,还需要配置好MQTT服务器的连接参数,包括broker地址、clientId等。另外,在使用完MQTT客户端后,需要及时关闭和断开与服务器的连接,以释放资源。 ### 回答2: 在Android Studio中使用MQTT收发数据,步骤如下: 1. 导入MQTT库:在项目的build.gradle文件中添加MQTT库的依赖项。可以使用Eclipse Paho库或者MQTT Android Service库。 2. 创建MQTT连接:通过编写代码创建MQTT Client对象,并设置连接参数,如服务器地址、端口号、客户端ID等。可以选择使用TLS/SSL进行安全连接。 3. 建立连接:使用connect()方法建立与MQTT服务器的连接。可以设置连接超时时间、断开重连策略。 4. 订阅主题:使用subscribe()方法订阅感兴趣的主题。可以设置订阅的QoS(服务质量),以控制传输质量和性能。 5. 发布消息:使用publish()方法发布消息到特定主题。可以设置消息的负载、QoS和保留标志。 6. 处理接收到的消息:通过实现MQTT Callback接口的方法来处理接收到的消息。可以根据主题和消息负载来执行相应的操作。 7. 断开连接:使用disconnect()方法断开与MQTT服务器的连接。可以在不使用连接时手动断开连接,或者监听网络变化动态断开连接。 8. 错误处理:处理连接错误、订阅失败、发布失败等异常情况。可以通过捕获异常、打印日志或者提供用户反馈来处理错误。 9. 线程管理:为了避免网络通信阻塞主线程,建议将MQTT操作放在后台线程中进行,可以使用AsyncTask或者其他多线程处理方式。 10. 资源回收:在不使用MQTT连接时,及时释放资源,关闭连接,并释放相关对象,以节省系统资源。 以上是使用Android Studio进行MQTT收发数据的基本步骤。根据实际需求,还可以添加其他功能,如持久化订阅、离线消息处理、消息过滤等。
评论 13
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

第四维度4

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值