mqtt安卓客户端

1.MQTT(消息队列遥测传输协议),是一种基于 发布/订阅 (publish/subscribe)模式的"轻量级"通讯协议, 该协议构建于TCP/IP协议上 。MQTT最大优点在于,可以以极少的代码和有限的带宽,为连接远程设备提供实时可靠的消息服务。作为一种低开销、低带宽占用的即时通讯协议,使其在物联网、小型设备、移动应用等方面有较广泛的应用。

MQTT协议中有三种身份:发布者(Publish)、服务器(Broker)、订阅者(Subscribe)

2.api操作:
Connect:与服务器进行MQTT连接;
Disconnect:与服务器断开MQTT连接;
Subscribe:订阅某个主题;
UnSubscribe:取消订阅某个主题;
Publish:发布消息;

3.安卓客户端示例:

添加依赖:

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

添加权限

<uses-permission android:name="android.permission.INTERNET" />

java代码

//创建实例
//brokerUrl为实例,clientid是唯一值
MqttAndroidClient mqttAndroidClient = new MqttAndroidClient(context, brokerUrl, clientId);

 //设置监听订阅消息的回调
        mqttAndroidClient.setCallback(mqttCallback);
        mMqttConnectOptions = new MqttConnectOptions();
        //设置是否清除缓存
        mMqttConnectOptions.setCleanSession(true);
        //设置超时时间,单位:秒
        mMqttConnectOptions.setConnectionTimeout(60);
        //设置心跳包发送间隔,单位:秒
        mMqttConnectOptions.setKeepAliveInterval(60);
        //设置用户名
        mMqttConnectOptions.setUserName(userName);
        //设置密码
        mMqttConnectOptions.setPassword(password.toCharArray());
        //是否重连
        mMqttConnectOptions.setAutomaticReconnect(false);
        //同时发布的最大消息数量
        mMqttConnectOptions.setMaxInflight(10000);

//建立连接
 mqttAndroidClient.connect(mMqttConnectOptions, null, iMqttActionListener);

  private final MqttCallback mqttCallback = new MqttCallback() {

           //这里处理收到的数据
        @Override
        public void messageArrived(String topic, MqttMessage message) {
       
        }

        @Override
        public void deliveryComplete(IMqttDeliveryToken arg0) {
            Log.d(TAG, "deliveryComplete: ");
        }

        @Override
        public void connectionLost(Throwable arg0) {
            Log.e(TAG, "connectionLost:" + arg0.getMessage());
            Log.e(TAG, "onFailure: " + mqttAndroidClient.isConnected());
            doReconnect();
        }

    };


 private final IMqttActionListener iMqttActionListener = new IMqttActionListener() {
        @Override
        public void onSuccess(IMqttToken arg0) {
           //建立订阅
            try {
                mqttAndroidClient.subscribe(topic, topicQos, null,
                        new IMqttActionListener() {
                            @Override
                            public void onSuccess(IMqttToken asyncActionToken) {
                                Log.d(TAG, "Subscribed topic successfully: " + asyncActionToken
                                        .toString());
                            }

                            @Override
                            public void onFailure(IMqttToken asyncActionToken,
                                                  Throwable exception) {
                                Log.d(TAG, "Failed to subscribe to a topic: " + asyncActionToken
                                        .toString());
                            }

                        });
            } catch (MqttException e) {
                Log.d(TAG, "Subscribe to the topic: " + e);
                e.printStackTrace();
            }
        }

        @Override
        public void onFailure(IMqttToken arg0, Throwable arg1) {
            arg1.printStackTrace();
            Log.e(TAG, "iMqttActionListener: arg0:" + arg0.toString() + " arg1:" + arg1
                    .getMessage());
            Log.e(TAG, "onFailure: " + mqttAndroidClient.isConnected());
            doReconnect();
        }
    };



MqttMessage message = new MqttMessage();
            message.setPayload(payload.getBytes());
            message.setQos(0);

//publish到mqtt
 mqttAndroidClient.publish(mTopic, message, null, new IMqttActionListener() {
                @Override
                public void onSuccess(IMqttToken asyncActionToken) {
                    Log.i(TAG, "publish succeed!");
                    listener.onState(1);
                }

                @Override
                public void onFailure(IMqttToken asyncActionToken, Throwable exception) {
                    Log.i(TAG, "publish failed!");
                    listener.onState(2);
                }
            });


你可能感兴趣的:(mqtt)