我也是MQTT和PAHO 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 :(得分:1)
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);
}
}