2016-09-24 83 views
1

我剛開始在我的應用中使用MQTT Paho庫。 如何對該主題進行異步訂閱? (訂閱新線程) 然後實時接收數據並顯示。Android MQTT異步訂閱

這是我在MainActivity代碼,在主線程:

public void mqttConnect() { 
    final TextView textView = (TextView) findViewById(R.id.sub_Text_View); 
    String clientId = MqttClient.generateClientId(); 
    final MqttAndroidClient client = new MqttAndroidClient(this.getApplicationContext(), server, clientId); 
    client.setCallback(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 { 
      Log.d("NANADEV", message.toString()); 
      textView.setText(message.toString()); 

     } 

     @Override 
     public void deliveryComplete(IMqttDeliveryToken token) { 

     } 
    }); 

    MqttConnectOptions mqttConnectOptions = new MqttConnectOptions(); 
    mqttConnectOptions.setAutomaticReconnect(true); 
    mqttConnectOptions.setCleanSession(false); 

    try { 
     client.connect(mqttConnectOptions, null, new IMqttActionListener() { 
      @Override 
      public void onSuccess(IMqttToken asyncActionToken) { 

       final String topic = "testwork/value"; 
       int qos =0; 
       try { 
        IMqttToken subToken = client.subscribe(topic, qos); 
        subToken.setActionCallback(new IMqttActionListener() { 
         @Override 
         public void onSuccess(IMqttToken asyncActionToken) { 



         } 

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

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

      } 

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

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

謝謝!

+0

你還沒有告訴我們爲什麼這是行不通的。編輯問題並解釋當您嘗試共享代碼時遇到的問題 – hardillb

回答

0

在你的OnCreate

private String uniqueID; 
String ip="brokerip"; 
String port="brokerport usaly 1883" 
String broker = "tcp://" + ip + ":" + port; 

uniqueID = android.provider.Settings.Secure.getString(getContentResolver(), android.provider.Settings.Secure.ANDROID_ID); 

IMqttAsyncClient client= new MqttAsyncClient(broker, uniqueID, new MemoryPersistence()); 
mqttClient.subscribe("YOURTOPIC/", 0); 
mqttClient.subscribe("YOUROTHERTOPIC", 0); 

,然後在你的方法:

public void messageArrived(String topic, MqttMessage msg) throws Exception { 
    Log.i("mqttarrival", "Message arrived from topic " + topic); 

    if (topic.equals("YOURTOPIC")) { 
     System.out.println(msg.toString()); 
    }  
    else { 
    } 
} 
+1

歡迎使用Stack Overflow!我建議你[參觀](http://stackoverflow.com/tour)。 –