Android MQTT异步订阅

时间:2016-09-24 17:57:42

标签: android asynchronous mqtt paho subscribe

我刚开始在我的应用程序中使用MQTT Paho库。 如何异步订阅主题? (在新主题中订阅) 然后实时接收数据并显示。

这是我在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();
    }

谢谢!

1 个答案:

答案 0 :(得分: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 {
    }
}