Basic Android Chat App using MQTT Part One

Posted By : Sobraj Yumkhaibam | 12-May-2016

This blog covers a part of the Android MQTT implementation of chat. I would be providing a small glimpse of how an MQTT connection can be established with a server. 
MQTT chat can be implemented in the following way:

Step 1: Include the following dependencies in your build.gradle app file-

    compile('org.eclipse.paho:org.eclipse.paho.android.service:1.0.2') {
        exclude module: 'support-v4'
        }
        compile 'org.eclipse.paho:org.eclipse.paho.client.mqttv3:1.0.2'

 

Step 2: A user establishes a connection with MQTT as follows-


   public void connectAction() {
        MqttConnectOptions conOpt = new MqttConnectOptions();
        String server = "iot.eclipse.org";
        String clientId = "abc";
        int port = 1883;
        boolean cleanSession = false;
        boolean ssl = false;
        String uri = null;
        uri = "tcp://";
        uri = uri + server + ":" + port;
        mqttAndroidClient = Connections.getInstance(chatActivity).createClient(chatActivity, uri, clientId);
        String clientHandle = uri + clientId;
        String username = "username";
        String password = "password";
        int timeout = 30;
        int keepalive = 60;
        connection = new Connection(clientHandle, clientId, server, port, context, mqttAndroidClient, ssl);
         connection.registerChangeListener(changeListener);
            String[] actionArgs = new String[1];
              actionArgs[0] = clientId;
        connection.changeConnectionStatus(Connection.ConnectionStatus.CONNECTING);
        conOpt.setCleanSession(cleanSession);
        conOpt.setConnectionTimeout(timeout);
        conOpt.setKeepAliveInterval(keepalive);
        if (!username.equals(ActivityConstants.empty)) {
            conOpt.setUserName(username);
        }
        if (!password.equals(ActivityConstants.empty)) {
            conOpt.setPassword(password.toCharArray());
        }
        final ActionListener callback = new ActionListener(chatActivity, context, ActionListener.Action.CONNECT,             clientHandle,actionArgs);
        boolean doConnect = true;
        mqttAndroidClient.setCallback(new MqttCallbackHandler(context, clientHandle));
        mqttAndroidClient.setTraceCallback(new MqttTraceCallback());
        connection.addConnectionOptions(conOpt);
        Connections.getInstance(context).addConnection(connection);
        if (doConnect) {
            try {
                mqttAndroidClient.connect(conOpt, null, callback);
            } catch (MqttException e) {
                Log.e(context.getClass().getCanonicalName(),
                        "MqttException Occurred", e);
            } catch (Exception e) {
            }
        }
    }


Here, changeListener is an instance of the class ChangeListener:

//class to get received message from MqttCallbackHandler's onMessageArrived method
 class ChangeListener implements PropertyChangeListener {
        @Override
        public void propertyChange(PropertyChangeEvent event) {
            chatActivity.runOnUiThread(new Runnable() {
                @Override
                public void run() {
                 //Code here to check if your connection callback has triggered a change in the property of the connection established
        //Use a method here to get the message received
                 }
            });
        }
    }

 

    The remaining classes involved are available at the following repo:

    https://github.com/jeffprestes/AndroidMQTTDemo/tree/master/app/src/main/java/org/eclipse/paho/android/service/sample


    Note that the parameters defined and required to establish a connection can be customised according to the need of different scenario.
    I would be covering the further implementation to subscribe to a topic, publish a message and disconnect from MQTT in the next blog
    "Basic Android Chat App using MQTT Part Two". Before going to the next blog, check if you could make a connection first. For any assistance, you may refer the link:

    http://www.hivemq.com/blog/mqtt-client-library-enyclopedia-paho-android-service


    THANKS

About Author

Author Image
Sobraj Yumkhaibam

Sobraj has been developing Android applications for a while now and is expert in mobile application development . He excels in developing mobile applications with location based intelligence. He loves Modelling as a hobby.

Request for Proposal

Name is required

Comment is required

Sending message..