2016-09-24 87 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)。 –