【问题标题】:Subscribe to Multiple MQTT topics订阅多个 MQTT 主题
【发布时间】:2018-07-13 16:15:23
【问题描述】:

我遇到了一个问题,或者可能是因为我的编程背景太小,问题是关于订阅多个主题并在 android 的多个文本视图中显示订阅的主题

我以前是这样订阅的:

private void setSub()
{
    try{

        client.subscribe(topic,0);

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

然后我在连接MQTT客户端成功后调用了setsub()函数

然后我实现了 setCallBack 方法,并在 messageArrived 下添加了一行以使用从订阅中收到的消息有效负载更改 textview 值

@Override
public void messageArrived(String topic, MqttMessage message) throws Exception {
    temp.setText(new String(message.getPayload()));
}

当然,当我定义另一个文本视图时,它的结果与第一个相同

所以我的问题是如何配置 MessageArrived 函数以在单个文本视图中显示每个主题?

提前谢谢你。

【问题讨论】:

    标签: java android mqtt paho subscribe


    【解决方案1】:

    您可以根据不同主题多次致电client.subscribe()。

    private void setSub()
    {
        try{
    
            client.subscribe(topic1,0);
            client.subscribe(topic2,0);
            client.subscribe(topic3,0);
    
        }
        catch (MqttException e){
            e.printStackTrace();
        }
    }
    

    messageArrived() 回调为每条消息传递topic,因此您只需设置一个 if 语句来决定根据主题更新哪个 textView。

    @Override
    public void messageArrived(String topic, MqttMessage message) throws Exception {
      if (topic.equals(topic1) {
        temp.setText(new String(message.getPayload()));
      } else if (topic.equals(topic2) {
        foo.setText(new String(message.getPayload()));
      }
    }
    

    但是你不应该在回调中调用setText() 方法,因为它发生在客户端线程上。您需要查看使用runOnUiThread() 进行更新。

    【讨论】:

      【解决方案2】:

      我刚刚想通了,

      if (topic.contains("button") ) {
                  temp.setText(new String(message.getPayload()));
              }
              else if (topic.contains("test"))
              {
                  volt.setText(new String(message.getPayload()));
              }
      

      我刚刚输入了我想显示的每个主题的名称。

      【讨论】:

        【解决方案3】:

        试试 runOnUiThread 方法,因为 onMessageArived() 是一个客户端线程。

        public void messageArrived(String topic, MqttMessage message) 
        throws Exception {
            String msg = new String(message.getPayload());
            Log.i(TAG, "Message Arrived: " + msg);
            runOnUiThread(new Runnable(){
                public void run() {
                    textView.setText(msg);
                }
            });
        }    
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2021-08-24
          • 1970-01-01
          • 2016-06-10
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2021-12-22
          • 1970-01-01
          相关资源
          最近更新 更多