在不同的textview中订阅多个主题

时间:2018-11-09 18:12:46

标签: android mqtt subscribe

我正在按照本教程使用MQTT协议创建项目:

https://wildanmsyah.wordpress.com/2017/05/11/mqtt-android-client-tutorial/

但是,我想知道如何在其他textview中订阅来自不同主题的不同消息。例如:

message1从topic1到textview1, 从topic2到textview2的message2, 从主题3到textview3的message3 ... 我想用来自不同主题的不同消息创建不同的textview。

谢谢大家! =)

在我的MQTTHelper.java中:

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

            }

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

            }
        });


    }

    catch (MqttException ex) {
        System.err.println("Exception whilst subscribing");
        ex.printStackTrace();
    }

    try {
        mqttAndroidClient.subscribe(subscriptionTopic2, 0, null, new IMqttActionListener() {
            @Override
            public void onSuccess(IMqttToken asyncActionToken) {

            }

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

            }
        });


    }

    catch (MqttException ex) {
        System.err.println("Exception whilst subscribing");
        ex.printStackTrace();
    }

}

在我的MainActivity中:

 private  void startMqtt(){

    mqttHelper = new MQTTHelper(getApplicationContext());
    mqttHelper.setCallback(new MqttCallback() {
        @Override
        public void connectionLost(Throwable cause) {

        }

        @Override
        public void messageArrived(String topic, MqttMessage message) throws Exception {
        textReceive.setText(message.toString());
        }



        @Override
        public void deliveryComplete(IMqttDeliveryToken token) {

        }
    });


    mqttHelper2 = new MQTTHelper(getApplicationContext());
    mqttHelper2.setCallback(new MqttCallback() {
        @Override
        public void connectionLost(Throwable cause) {

        }

        @Override
        public void messageArrived(String topic, MqttMessage message) throws Exception {
        textReceive2.setText(message.toString());
        }

        @Override
        public void deliveryComplete(IMqttDeliveryToken token) {

        }
    });


}

0 个答案:

没有答案