Android 中使用MQTT

一、简介
MQTT是一个客户端服务端架构的发布/订阅模式的消息传输协议。它的设计思想是轻巧、开放、简单、规范,易于实现。这些特点使得它对很多场景来说都是很好的选择,特别是对于受限的环境如机器与机器的通信(M2M)以及物联网环境(IoT)。
二、MQTT资源
github地址
官方文档
中文翻译
三、AndroidStudio集成
引用资源

repositories {
maven {
    url "https://repo.eclipse.org/content/repositories/paho-snapshots/"
}
}
dependencies {
   implementation 'org.eclipse.paho:org.eclipse.paho.client.mqttv3:1.1.0'
   implementation 'org.eclipse.paho:org.eclipse.paho.android.service:1.1.1'
}

声明权限




注册服务


四、MQTT封装

import android.content.Context;
import org.eclipse.paho.android.service.MqttAndroidClient;
import org.eclipse.paho.client.mqttv3.DisconnectedBufferOptions;
import org.eclipse.paho.client.mqttv3.IMqttActionListener;
import org.eclipse.paho.client.mqttv3.IMqttToken;
import org.eclipse.paho.client.mqttv3.MqttCallback;
import org.eclipse.paho.client.mqttv3.MqttConnectOptions;
import org.eclipse.paho.client.mqttv3.MqttException;
import org.eclipse.paho.client.mqttv3.MqttMessage;
public class MQTTHelper {

    private static final String SERVER_URI = "服务地址";
    private static final String CLIENT_ID = "ID唯一标识";

    private static final String USER_NAME = "用户名";
    private static final String PASSWORD = "密码";

    private String mTopic;
    private boolean isConnected;
    private MqttAndroidClient mClient;

    public MQTTHelper(Context context, String topic, MqttCallback mqttCallback) {
        this.mTopic = topic;
        this.mClient = new MqttAndroidClient(context.getApplicationContext(), SERVER_URI, CLIENT_ID);
        if (mqttCallback != null) {
            this.mClient.setCallback(mqttCallback);
        }
    }

    /**
     * 触发连接
     */
    public void doConnect() {
        MqttConnectOptions connectOptions = new MqttConnectOptions();
        connectOptions.setUserName(USER_NAME);
        connectOptions.setPassword(PASSWORD.toCharArray());
        connectOptions.setAutomaticReconnect(true);
        //设置是否清除session,清除后服务器不会保留记忆
        connectOptions.setCleanSession(false);
        //设置超时时间,默认30s
        connectOptions.setConnectionTimeout(45);
        //设置心跳时间,默认60s
        connectOptions.setKeepAliveInterval(30);
        try {
            mClient.connect(connectOptions, null, new IMqttActionListener() {
                @Override
                public void onSuccess(IMqttToken asyncActionToken) {
                    isConnected = true;
                    DisconnectedBufferOptions disconnectedBufferOptions =
                            new DisconnectedBufferOptions();
                    disconnectedBufferOptions.setBufferEnabled(true);
                    disconnectedBufferOptions.setBufferSize(100);
                    disconnectedBufferOptions.setPersistBuffer(false);
                    disconnectedBufferOptions.setDeleteOldestMessages(false);
                    mClient.setBufferOpts(disconnectedBufferOptions);
                    subscribeToTopic();
                }

                @Override
                public void onFailure(IMqttToken asyncActionToken, Throwable exception) {
                    isConnected = false;
                }
            });

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

    private void subscribeToTopic() {
        try {
            mClient.subscribe(mTopic, 0, null, new IMqttActionListener() {
                @Override
                public void onSuccess(IMqttToken asyncActionToken) {
                }

                @Override
                public void onFailure(IMqttToken asyncActionToken, Throwable exception) {
                }
            });

        } catch (MqttException ex) {
            ex.printStackTrace();
        }
    }
    
    public void publish(String topic, MqttMessage mqttMessage) {
        if(mClient!=null && isConnected) {
            try {
                mClient.publish(topic,mqttMessage);
            } catch (MqttException e) {
                e.printStackTrace();
            }
        }
    }

    public void disconnect() {
        try {
            if (mClient != null & isConnected) {
                mClient.disconnect();
                this.isConnected = false;
            }
        } catch (MqttException e) {
            e.printStackTrace();
        }
    }
}

你可能感兴趣的:(安卓)