public class MqttService extends Service implements MqttCallback {
public MqttAsyncClient mClient;
mOpts = new MqttConnectOptions();
mOpts.setCleanSession(MQTT_CLEAN_SESSION);
mOpts.setUserName(String.valueOf(userMigration.getId()));
mOpts.setPassword(userMigration.getPassword().toCharArray());
mOpts.setAutomaticReconnect(true);
mOpts.setKeepAliveInterval(MQTT_KEEP_ALIVE);
mClient.connect(mOpts, this, connectListener);
@Override
public void messageArrived(String topic, MqttMessage message) throws Exception {
}
@Override
public void deliveryComplete(IMqttDeliveryToken token) {
//Log.e(DEBUG_TAG, "Completed Delivery");
}
@Override
public void connectionLost(Throwable arg0) {
stopKeepAlives();
Log.e(DEBUG_TAG, "Lost");
mClient = null;
}
IMqttActionListener connectListener = new IMqttActionListener() {
public void onSuccess(IMqttToken asyncActionToken) {
mStarted = true; // Service is now connected
Log.i(DEBUG_TAG,"Successfully connected");
mClient.setCallback(MqttService.this);
}
public void onFailure(IMqttToken asyncActionToken, Throwable exception) {
Log.e(DEBUG_TAG, "con failed "+exception.toString());
}
};
mClient.publish("message/"+jsonObject.get("userBId").getAsInt(),jsonObject.toString().getBytes(), 1, false, this, new IMqttActionListener() {
@Override
public void onSuccess(IMqttToken asyncActionToken) {
}
@Override
public void onFailure(IMqttToken asyncActionToken, Throwable exception) {
Log.e(DEBUG_TAG,"failed");
}
});
}
//如果我在连接后没有设置回调,它工作正常但收到的消息没有触发。如果我在连接后设置回调,它们到达的消息是触发但在发布期间,我得到了在null上定义的IMqttActionListener。你可以帮帮我吗。我需要在发布之后回调以更新数据库中的数据。
答案 0 :(得分:0)
尝试在启动连接之前移动mClient.setCallback(MqttService.this);
行:
mOpts.setKeepAliveInterval(MQTT_KEEP_ALIVE);
mClient.setCallback(this);
mClient.connect(mOpts, this, connectListener);