Mqtt鏈接狀態監聽

private void mqttCallbackDemo(){
    MqttCallback callback=  new MqttCallback(){

        @Override
        public void connectionLost(Throwable cause) {
            //鏈接丟失
        }

        @Override
        public void messageArrived(String topic, MqttMessage message) throws Exception {
            //接收到消息
        }

        @Override
        public void deliveryComplete(IMqttDeliveryToken token) {
            // 成功發出消息
        }
    };

    MqttCallbackExtended callbackExtended = new MqttCallbackExtended() {
        @Override
        public void connectComplete(boolean reconnect, String serverURI) {
            // 鏈接成功
        }

        @Override
        public void connectionLost(Throwable cause) {
            //鏈接丟失
        }

        @Override
        public void messageArrived(String topic, MqttMessage message) throws Exception {
            //接收到消息
        }

        @Override
        public void deliveryComplete(IMqttDeliveryToken token) {
            // 成功發出消息
        }
    };

    MqttAndroidClient mMqttAndroidClient = new MqttAndroidClient(this, "serverURI", "clientId");
    // 1 這種沒法接收到鏈接成功的回調
    mMqttAndroidClient.setCallback(callback);
    // 能夠接收到鏈接成功的回調
    mMqttAndroidClient.setCallback(callbackExtended);
    
    // 若是須要實時監聽mqtt鏈接狀態,須要使用MqttCallbackExtended,不然只能監聽到鏈接丟失,
    //而收不到自動鏈接成功的消息
}
相關文章
相關標籤/搜索