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");
}
});
}
//If I am not setting callback after connection, it is working perfectly but message recevied is not triggering. If I set callback after connection, them message arrived is triggering but during publish, I am getting IMqttActionListener defined on null. Could you help me. I need callback just after the publish to update that data in my database.
Try moving the
mClient.setCallback(MqttService.this);
line up, before connect is initiated: