Android 实现MQTT客户端,用于门禁消息推送

本文详细介绍了在Android应用中使用MQTT协议的客户端和服务端实现,包括MqttClient的连接、订阅、发布消息以及MqttAndroidClientService的配置和处理连接丢失、重连和断开情况,同时涉及CleanSession和自动重连选项的设置。

添加MQTT依赖

implementation ‘org.eclipse.paho:org.eclipse.paho.client.mqttv3:1.2.2’
implementation ‘org.eclipse.paho:org.eclipse.paho.android.service:1.1.1’

在Manifest清单文件中添加服务

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

两种实现方法


MqttClient的实现方式

MQTT初始化连接线程,实现与服务器的连接、订阅、发布消息
    private class ConnectTask extends AsyncTask<Void, String, Boolean> {
   
   
        //MQTT连接线程,实现与服务器的连接、订阅、发布消息
        /**
         * 异步任务:AsyncTask<Params, Progress, Result>
         * 1.Params:UI线程传过来的参数。
         * 2.Progress:发布进度的类型。
         * 3.Result:返回结果的类型。耗时操作doInBackground的返回结果传给执行之后的参数类型。
         *
         * 执行流程:
         * 1.onPreExecute()
         * 2.doInBackground()-->onProgressUpdate()
         * 3.onPostExecute()
         */

        @Override
        protected void onPreExecute() //执行耗时操作之前处理UI线程事件
        {
   
   
            super.onPreExecute();
            isConnecting = true;
            connectionStatusTextView.setText("Connecting...");
        }

        @Override
        protected Boolean doInBackground(Void... voids)
        {
   
   
            //在此方法执行耗时操作,耗时操作中收发MQTT服务器的数据
            //MQTT服务器地址
            String brokerUrl = "tcp://www.10086.com:1883";
            //客户端ID,用于在MQTT服务器上
            String clientId = MqttClient.generateClientId();
            try {
   
   
                mqttClient = new MqttClient(brokerUrl, clientId, new MemoryPersistence());
            } catch (MqttException e) {
   
   
                throw new RuntimeException(e);
            }
            MqttConnectOptions connectOptions = new MqttConnectOptions();
            connectOptions.setCleanSession(true);
            //mqtt服务器用户名和密码
            connectOptions.setUserName("username");
            connectOptions.setPassword("password".toCharArray());
            connectOptions.setWill("断线消息主题","断线消息内容".getBytes(),1,true);
            connectOptions.setConnectionTimeout(10);
            connectOptions.setKeepAliveInterval(20);
            try {
   
   
                mqttClient.connect(connectOptions);
                mqttClient.setCallback(new MqttCallback() {
   
   
                    @Override
                    public void connectionLost(Throwable throwable) {
   
   
                        Log.e(TAG, "连接丢失");//连接丢失的时候可以在这里进行重新连接
                        publishProgress("Connection lost, reconnecting...");
                        new ReconnectTask().execute();
                    }

                    @Override
                    public void messageArrived(String topic, MqttMessage message) throws Exception {
   
   
                        Log.i(TAG, "收到消息:"+message.toString());
                        if (topic.equals("sensors/temperature")) {
   
   
                            // Update temperature reading
                            publishProgress("Temperature: " + message.toString());
                        } else if (topic.equals("sensors/humidity")) {
   
   
                            // Update humidity reading
                            publishProgress("Humidity: " + message.toString());
                        } else if (topic.equals("leds/led1/status")) {
   
   
                            // Update LED 1 status
                            if (message.toString().equals("on")) {
   
   
                                publishProgress("LED 1 is on");
                                ledStatusImageView.setText("LED 1 is on");
                            } else {
   
   
                                publishProgress("LED 1 is off");
                                ledStatusImageView.setText("LED 1 is off");
                            }
                        } else if (topic.equals("leds/led2/status")) {
   
   
                            // Update LED 2 status
                            if (message.toString().equals("on")) {
   
   
                                publishProgress("LED 2 is on");
                                ledStatusImageView.setText("LED 2 is on");
                            } else {
   
   
                                publishProgress("LED 2 is off");
                                ledStatusImageView.setText("LED 2 is off");
                            }
                        }
                    }

                    @Override
                    public void deliveryComplete(
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值