【问题标题】:how to receive message in mqtt android如何在 mqtt android 中接收消息
【发布时间】:2017-07-27 11:21:53
【问题描述】:

我也是 MQTT 和 PAHO MQTT 客户端库的新手。我可以成功连接,但是当我订阅时,我无法收到成功消息。这是我的代码

    String topic = "test123";
    int qos = 2;
    try {
        IMqttToken subToken = client.subscribe(topic, qos);
        subToken.setActionCallback(new IMqttActionListener() {
            @Override
            public void onSuccess(IMqttToken asyncActionToken) {
                // The message was published
            }


            @Override
            public void onFailure(IMqttToken asyncActionToken,
                                  Throwable exception) {
                // The subscription could not be performed, maybe the user was not
                // authorized to subscribe on the specified topic e.g. using wildcards

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

【问题讨论】:

  • 您发布的代码只是请求订阅,您需要添加回调来处理实际的消息到达。
  • 你有解决方案吗,我也在尝试同样的方法,但无法成功?

标签: android mqtt


【解决方案1】:
   public void subscribeMqttChannel(String channelName) {
    try {
       Log.d("tag","mqtt channel name>>>>>>>>" + channelName);
       Log.d("tag","client.isConnected()>>>>>>>>" + client.isConnected());
        if (client.isConnected()) {
            client.subscribe(channelName, 0);
            client.setCallback(new MqttCallback() {
                @Override
                public void connectionLost(Throwable cause) {
                }

                @Override
                public void messageArrived(String topic, MqttMessage message) throws Exception {
                   Log.d("tag","message>>" + new String(message.getPayload()));
                   Log.d("tag","topic>>" + topic);
                    parseMqttMessage(new String(message.getPayload()));

                }

                @Override
                public void deliveryComplete(IMqttDeliveryToken token) {

                }
            });
        } 
    } catch (Exception e) {
        Log.d("tag","Error :" + e);
    }
}

【讨论】:

    猜你喜欢
    • 2016-03-13
    • 1970-01-01
    • 1970-01-01
    • 2021-10-15
    • 2018-05-05
    • 1970-01-01
    • 2023-03-24
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多