Android MQTT 使用详解

MQTT 使用

引入MQTT库

//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’

MqttManager

public class MqttManager {
    private static MqttManager mInstance = null;
    /**
     * Mqtt回调
     */
    private MqttCallback mCallback;
    /**
     * Mqtt客户端
     */
    private static MqttClient client;
    /**
     * Mqtt连接选项
     */
    private MqttConnectOptions conOpt;

    private MqttManager() {
        mCallback = new MqttCallbackBus();
    }

    public static MqttManager getInstance() {
        if (null == mInstance) {
            synchronized (MqttManager.class) {
                if (mInstance == null) {
                    mInstance = new MqttManager();
                }
            }
        }
        return mInstance;
    }

    /**
     * 释放单例, 及其所引用的资源
     */
    public static void release() {
        try {
            if (mInstance != null) {
                mInstance = null;
            }
        } catch (Exception e) {
            LogUtils.e("release : " + e.toString());
        }
    }

    /**
     * 创建Mqtt 连接
     *
     * @param clientId 客户端Id
     */
    public void creatConnect(String clientId,String topicId) {
        LogUtils.i("clientId"+clientId);
        // 获取默认的临时文件路径
        String tmpDir = System.getProperty("java.io.tmpdir");

        /*
         * MqttDefaultFilePersistence:
         * 将数据包保存到持久化文件中,
         * 在数据发送过程中无论程序是否奔溃、 网络好坏
         * 只要发送的数据包客户端没有收到,
         * 这个数据包会一直保存在文件中,
         * 直到发送成功为止。
         */
        // Mqtt的默认文件持久化
        MqttDefaultFilePersistence dataStore = new MqttDefaultFilePersistence(tmpDir);
        try {
            // 构建包含连接参数的连接选择对象
            conOpt = new MqttConnectOptions();
            // 设置Mqtt版本
            conOpt.setMqttVersion(MqttConnectOptions.MQTT_VERSION_3_1_1);
            // 设置清空Session,false表示服务器会保留客户端的连接记录,true表示每次以新的身份连接到服务器
            conOpt.setCleanSession(false);//是否要保留连接记录?

            // 设置账号
            conOpt.setUserName(MQTTName);
            // 设置密码
            conOpt.setPassword(MQTTPassWord.toCharArray());

            // 设置超时时间,单位:秒
            conOpt.setConnectionTimeout(10);
            // 设置会话心跳时间,单位为秒
            // 客户端每隔120秒向服务端发送心跳包判断客户端是否在线
            conOpt.setKeepAliveInterval(120);
            // 客户端是否自动尝试重新连接到服务器
            conOpt.setAutomaticReconnect(true);
            // 创建MQTT客户端
            client = new MqttClient(MQTTURL, clientId, dataStore);
            // 设置回调
            client.setCallback(mCallback);
            // 最后的遗言(连接断开时, 发动"close"给订阅了topic该主题的用户告知连接已中断)
            conOpt.setWill(topicId, "close".getBytes(), 1, true);
            // 连接
            doConnect();

        } catch (MqttException e) {
            LogUtils.e("creatConnect : " + e.toString());

        }

    }


    /**
     * 建立连接
     */
    public void doConnect() {
        if (client != null) {
            try {
                LogUtils.i("conOpt"+conOpt);
                client.connect(conOpt);
            } catch (Exception e) {
                LogUtils.e("doConnect : " + e.toString());
            }
        }
    }


    /**
     * 发布消息
     *
     * @param topicName 主题名称
     * @param qos       质量(0,1,2)
     * @param payload   发送的内容
     */
    public void publish(String topicName, int qos, byte[] payload) {
        if (client != null && client.isConnected()) {
            // 创建和配置一个消息
            MqttMessage message = new MqttMessage(payload);
            message.setPayload(payload);
            message.setQos(qos);
            try {
                client.publish(topicName, message);
            } catch (MqttException e) {
                LogUtils.e("publish : " + e.toString());
            }
        }
    }


    public void publish(String topicName, int qos, String payload) {
        if (client != null && client.isConnected()) {
            // 创建和配置一个消息
            MqttMessage message = new MqttMessage(payload.getBytes());
            message.setPayload(payload.getBytes());
            message.setQos(qos);
            try {
                client.publish(topicName, message);
            } catch (MqttException e) {
                LogUtils.e("publish : " + e.toString());
            }
        }
    }


    /**
     * 订阅主题
     *
     * @param topicName 主题名称
     * @param qos       消息质量
     */
    public void subscribe(String topicName, int qos) {
        if (client != null && client.isConnected()) {
            try {
                client.subscribe(topicName, qos);
            } catch (MqttException e) {
                LogUtils.e("subscribe : " + e.toString());
            }
        }
    }

    /**
     * 取消订阅
     */
    public void unsubscribe(String topicName) {
        if (client != null && client.isConnected()) {
            try {
                client.unsubscribe(topicName);
            } catch (MqttException e) {
                LogUtils.e("unsubscribe : " + e.toString());
            }
        }
    }


    /**
     * 取消连接
     */
    public static void disConnect() throws MqttException {
        if (client != null && client.isConnected()) {
            client.disconnect();
        }
    }


    /**
     * 判断是否连接
     */
    public static boolean isConnected() {
        return client != null && client.isConnected();
    }
}


MqttCallbackBus

public class MqttCallbackBus implements MqttCallbackExtended {
    // 可在此方法内写重连的逻辑
    @Override
    public void connectComplete(boolean reconnect, String serverURI) {
        LogUtils.i("connectComplete",reconnect);
        if (reconnect) {
           //重连的逻辑
            MqttManager.getInstance().subscribe(topicId, 1);
        }
    }

    /**
     * 连接中断
     */
    @Override
    public void connectionLost(Throwable cause) {
        LogUtils.e("连接中断: " + cause.toString());
    }


    /**
     * 消息送达
     */
    @Override
    public void messageArrived(String topic, MqttMessage message) throws Exception {
        LogUtils.e("topic : " + topic + "\t MqttMessage : " + message.toString());
        //收到的消息处理
        //EventBus.getDefault().post(messageEvent);
    }


    /**
     * 交互完成
     */
    @Override
    public void deliveryComplete(IMqttDeliveryToken token) {
        LogUtils.e( "交互完成:" + token.toString());
    }


}

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值