Sunday 5 March 2017

Android MQTT


This Blog has been migrated tohttps://medium.com/@gaikwadchetan93/android-real-time-communication-using-mqtt-9ea42551475d

MQTT
(Message Queue Telemetry Transport)

What is MQTT?
MQTT is a machine-to-machine (M2M)/"Internet of Things" connectivity protocol.

Used for simple communication between multiple devices with a simple messaging protocol in RealTime.

Some of the related concepts
    -Pub-Sub: publish-subscribe-based messaging protocol.
    -Broker: The broker is responsible for distributing messages to interested clients based on the topic of a message.


Some of the broker server tasks are
  -Receive all messages
  -Filter  and rectify the interesting subscriber
  -send/publish msg to all  subscriber
  
     -TopicA topic is a UTF-8 string, which is used by the broker to filter messages for each connected client. A topic consists of one or more topic levels. Each topic level is separated by a forward slash. eg:global/demo



Why not HTTP for this purpose?
-No Good solution for push and Quality of service
-Require more bandwidth
-Acting as host require more battery(To listen for incoming request and server)
-more battery

MQTT advantages
-Pub-Sub protocol
-Limited Bandwidth - It is designed for connections to remote locations where a "small code footprint" is required or the network bandwidth is limited
-Binary format requires less bandwidth
-Less battery





Lets jump into code how to implement MQTT in Android

Installation

To add the Paho Android Service as a dependency to you app add the following parts to your gradle file.
repositories {
    maven {
        url"https://repo.eclipse.org/content/repositories/paho-releases/"
   
}
}


dependencies {
compile 'org.eclipse.paho:org.eclipse.paho.client.mqttv3:1.1.0'

compile 'org.eclipse.paho:org.eclipse.paho.android.service:1.1.0'
}


In you manifiest file add below tag under <application>
<service android:name="org.eclipse.paho.android.service.MqttService"></service>

Add following permission




<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" />


Initialize

String clientId = MqttClient.generateClientId();
MqttAndroidClient client = new MqttAndroidClient(application, "BROKER SERVER",
        clientId);

1. Connect

void connectToMqtt(final MqttAndroidClient client) {
    try {
        IMqttToken token = client.connect();
        token.setActionCallback(new IMqttActionListener() {
            @Override
            public void onSuccess(IMqttToken asyncActionToken) {
              // We are connected
               Timber.d("On Mqtt connect success");
               subscribeToMqttChannel(client);
            }

            @Override
            public void onFailure(IMqttToken asyncActionToken, Throwable exception) {
              // Something went wrong e.g. connection timeout or firewall problems 
               Timber.d("On Mqtt connect failure %s",exception.getMessage());

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



void subscribeToMqttChannel(MqttAndroidClient client) {

    String topic = "demo";

    int qos = 1;

    try {

        IMqttToken subToken = client.subscribe(topic, qos, iMqttMessageListener);



    } catch (MqttException e) {

        e.printStackTrace();

    }

}



IMqttMessageListener iMqttMessageListener = new IMqttMessageListener() {

    @Override

    public void messageArrived(String topic, MqttMessage message) throws Exception {

        Timber.d("Message received %s",message);

        JSONObject signallStatus = new JSONObject(message.toString());



    }

};





 
3. UnSubscribe

void unSubscribeMqttChannel(MqttAndroidClient client) {

    final String topic = "demo";

    try {

        IMqttToken unsubToken = client.unsubscribe(topic);

        unsubToken.setActionCallback(new IMqttActionListener() {

            @Override

            public void onSuccess(IMqttToken asyncActionToken) {

                // The subscription could successfully be removed from the client

                Timber.d("On Mqtt unSubscribed");

            }



            @Override

            public void onFailure(IMqttToken asyncActionToken,

                                  Throwable exception) {

                // some error occurred, this is very unlikely as even if the client

                // did not had a subscription to the topic the unsubscribe action

                // will be successfully

                Timber.d("On Mqtt unSubscribe failure %s",exception.getMessage());

            }

        });

    } catch (MqttException e) {

        e.printStackTrace();

    }

}



4.Disconnect

void disconnectMqtt(MqttAndroidClient client) {

    try {

        IMqttToken token = client.disconnect();

        token.setActionCallback(new IMqttActionListener() {

            @Override

            public void onSuccess(IMqttToken asyncActionToken) {

                // We are connected

                Timber.d("On Mqtt disconnected");

            }



            @Override

            public void onFailure(IMqttToken asyncActionToken, Throwable exception) {

                // Something went wrong e.g. connection timeout or firewall problems

                Timber.d("On Mqtt disconnect failure %s",exception.getMessage());



            }

        });

    } catch (MqttException e) {

        e.printStackTrace();

    }

}




Usage
Facebook Messenger. Facebook has used aspects of MQTT in Facebook Messenger for online chat.However, it is unclear how much of MQTT is used or for what.

So I think we don't need to mention more example to understand the importance of MQTT above one is enough.




Try it yourself
 
Please suggest if any update.
 
Updates are always welcome
 
HAPPY CODING :)
 
 
 
source code  https://github.com/gaikwadChetan93/Android-MQTT-Demo

My Apps MobileUtility

No comments:

Post a Comment