Search code examples
androidmqttpaho

MQTT Android client not connecting to broker


I'm playing around with MQTT and Android, but I can't seem to connect the client to the broker. This is how the code looks like:

String clientId = MqttClient.generateClientId();
MqttAndroidClient client = new MqttAndroidClient(this, brokerIp, clientId);

client.setCallback(new MqttCallback() {
    @Override
    public void connectionLost(Throwable cause) {
        Log.i(TAG, "connectionLost");
    }

    @Override
    public void messageArrived(String topic, MqttMessage message) throws Exception {
        Log.i(TAG, "messageArrived");
    }

    @Override
        public void deliveryComplete(IMqttDeliveryToken token) {
        Log.i(TAG, "deliveryComplete");
    }
});

client.connect().setActionCallback(new IMqttActionListener() {
    @Override
    public void onSuccess(IMqttToken asyncActionToken) {
        Log.i(TAG, "Connection success");
    }

    @Override
    public void onFailure(IMqttToken asyncActionToken, Throwable exception) {
        Log.i(TAG, "Connection failed: ", exception);
    }
});

The problem is that none of the callbacks are ever triggered. Running mosquitto on verbose mode there are no connections coming in from this client, and checking the log I don't see any Exception raised.

I tried locally and on the cloud and it doesn't connect to any, while a client I have on the backend side can connect to both using the same host and port. What am I missing?


Solution

  • Turns out the MqttService needs to be declared in the manifest to be able to bind to the Paho Android Service correctly:

    <service android:name="org.eclipse.paho.android.service.MqttService"/>