2017-07-27 108 views
0

我是新進MQTT和泛美衛生組織MQTT客戶機庫too.I是能夠成功連接,但是當我訂閱我不能夠得到message.Here是我的代碼如何在Android的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(); 

} 

+0

你已經發布的代碼只有約申請預訂的,你需要添加回調來處理實際的消息到來。 – hardillb

+0

謝謝@hardillb –

+0

你有解決方案嗎,我正在嘗試同樣的事情,但無法使其工作? –

回答

0
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); 
    } 
} 
相關問題