Android

Connect

 

As already mentioned, the Paho Android Service encapsulates the MQTT connection and offers an API for that. To be able to create a binding to the Paho Android Service, the service needs to be declared in the AndroidManifest.xml. Add the following within the tag:

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

The Paho Android Service needs the following permissions to work:

<uses-permission android:name="android.permission.WAKE_LOCK" />
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.READ_PHONE_STATE" />

 

Add those to the tag.

Usually an Android Activity requests or binds to an Android Service to use it, for e.g. the LocationManager to receive updates when the GPS position of the user changes. The Paho Android Service is not meant to bind to directly. Instead the provided MqttAndroidClient client interface binds to the service once created. To create and establish an MQTT-connection use the following code snipped:

String clientId = MqttClient.generateClientId();
MqttAndroidClient client =
        new MqttAndroidClient(this.getApplicationContext(), "tcp://broker.hivemq.com:1883",
                              clientId);

try {
    IMqttToken token = client.connect();
    token.setActionCallback(new IMqttActionListener() {
        @Override
        public void onSuccess(IMqttToken asyncActionToken) {
            // We are connected
            Log.d(TAG, "onSuccess");
        }

        @Override
        public void onFailure(IMqttToken asyncActionToken, Throwable exception) {
            // Something went wrong e.g. connection timeout or firewall problems
            Log.d(TAG, "onFailure");

        }
    });
} catch (MqttException e) {
    e.printStackTrace();
}

In the first line a helper Function of the Paho MQTT client is used to generate a random user id. The second line creates an instance of an Android MQTT client, that will bind to the Paho Android Service. By calling the connect method of the MqttAndroidClient the client will asynchronously try to connect to the MQTT broker and return a token. That token can be used to register callbacks, to get notified when either the MQTT-connection gets connected or an error occurs. Running the above example inside an Android Activity.onCreate method will print “onSuccess” or “onFailure” to the console.

 

Connect with MQTT 3.1 or MQTT 3.1.1

 

The MqttAndroidClient will connect with MQTT 3.1.1 by default, with a fallback to 3.1. To intentionally connect with MQTT 3.1 a MqttConnectOptions object can be supplied to the connect method:

MqttConnectOptions options = new MqttConnectOptions();
options.setMqttVersion(MqttConnectOptions.MQTT_VERSION_3_1);
IMqttToken token = client.connect(options);