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();
}
谢谢!
你还没有告诉我们为什么这是行不通的。编辑问题并解释当您尝试共享代码时遇到的问题 – hardillb