MQTT Publish/Subscribe Demo - Android

hello buddies,

Today we are going to learn about mqtt protocol in android.

MQTT is publish-subscribe-based messaging protocol. It works on top of the TCP/IP protocol. It's design for communication between device and os. in this blog today we  are going to learn about connection of mqtt and  subscribe message and publish message in android.


First of all we need to add some maven repositories and compile lib in android.


1)  maven {
    url "https://repo.eclipse.org/content/repositories/paho-snapshots/"    }


2)  compile 'org.eclipse.paho:org.eclipse.paho.client.mqttv3:1.1.0'   
     compile 'org.eclipse.paho:org.eclipse.paho.android.service:1.1.1'

Now we need to add some permission and service in android.

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

 Add this service in AndroidMainfest.xml file.

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

activity_main.xml


<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"    
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">

<EditText
android:id="@+id/editmqttsendmsg"        
android:layout_width="match_parent"        
android:layout_height="wrap_content"
android:layout_marginLeft="20dp"        
android:layout_marginRight="20dp"        
android:layout_marginTop="50dp"
android:hint="MQTT Message" />

<TextView
android:id="@+id/txtmqttmessage"        
android:layout_width="wrap_content"
android:layout_height="wrap_content"        
android:layout_below="@id/editmqttsendmsg"
android:layout_centerHorizontal="true"
android:layout_marginTop="10dp"        
android:text="Subscribe Message"        
android:textSize="20dp" />

<Button        
android:layout_width="wrap_content"       
android:layout_height="wrap_content"       
android:layout_below="@id/txtmqttmessage"       
android:layout_centerHorizontal="true"       
android:layout_marginTop="20dp"       
android:text="Publish Message"       
android:id="@+id/btnpubmsg"/>
</RelativeLayout>


MainActivity.java


public class MainActivity extends AppCompatActivity {

    TextView mqttmessage;
    EditText editmqttsendmsg;
    Button btnpublishmsg;
    MQTTHelperClass mqttHelperClass;
    @Override    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        mqttmessage = (TextView) findViewById(R.id.txtmqttmessage);
        editmqttsendmsg = (EditText)findViewById(R.id.editmqttsendmsg);
        btnpublishmsg = (Button)findViewById(R.id.btnpubmsg);
        btnpublishmsg.setOnClickListener(new View.OnClickListener() {
            @Override            public void onClick(View v) {
                mqttHelperClass = new MQTTHelperClass(MainActivity.this);
                String msg = editmqttsendmsg.getText().toString();
                if (msg != null) {
                    try {
                        mqttHelperClass.publishMessage(msg);
                    } catch (MqttException e) {
                        e.printStackTrace();
                    } catch (UnsupportedEncodingException e) {
                        e.printStackTrace();
                    }
                }else {
                    Toast.makeText(getApplicationContext(),"Please insert MEssage first",Toast.LENGTH_SHORT).show();
                }
            }
        });
        startMQTTRecevier();
    }
    private void startMQTTRecevier() {
        mqttHelperClass = new MQTTHelperClass(MainActivity.this);
        mqttHelperClass.setCallback(new MqttCallbackExtended() {
            @Override            
            public void connectComplete(boolean b, String s) {
            }
            @Override            
            public void connectionLost(Throwable throwable) {
            }
            @Override            
            public void messageArrived(String topic, MqttMessage mqttMessage) throws Exception {
                Log.w("Debug", mqttMessage.toString());
                mqttmessage.setText(mqttMessage.toString());
            }
            @Override            
            public void deliveryComplete(IMqttDeliveryToken iMqttDeliveryToken) {
            }
        });
    }
}



MQTTHelperClass.java


public class MQTTHelperClass {
    public MqttAndroidClient mqttAndroidClient;
    final String serverUri = "serverurl";
    final String clientId = "ExampleAndroidClient";
    final String subscriptionTopic = "mqttmsg/+";
    final String username = "username";
    final String password = "passwprd";
    public MQTTHelperClass(Context context){
        mqttAndroidClient = new MqttAndroidClient(context, serverUri, clientId);
        mqttAndroidClient.setCallback(new MqttCallbackExtended() {
            @Override

            public void connectComplete(boolean b, String s) {
                Log.w("mqtt", s);
            }

            @Override

            public void connectionLost(Throwable throwable) {
            }
            @Override
            public void messageArrived(String topic, MqttMessage mqttMessage) throws Exception {
                Log.w("Mqtt", mqttMessage.toString());
            }
            @Override
            public void deliveryComplete(IMqttDeliveryToken iMqttDeliveryToken) {
            }
        });
        connect();
    }
    public void setCallback(MqttCallbackExtended callback) {
        mqttAndroidClient.setCallback(callback);
    }

    private void connect(){
        MqttConnectOptions mqttConnectOptions = new MqttConnectOptions();
        mqttConnectOptions.setAutomaticReconnect(true);
        mqttConnectOptions.setCleanSession(false);
        mqttConnectOptions.setUserName(username);
        mqttConnectOptions.setPassword(password.toCharArray());

        try {
            mqttAndroidClient.connect(mqttConnectOptions, null, new IMqttActionListener() {
                @Override
                public void onSuccess(IMqttToken asyncActionToken) {
                    DisconnectedBufferOptions disconnectedBufferOptions = new      DisconnectedBufferOptions();
                    disconnectedBufferOptions.setBufferEnabled(true);
                    disconnectedBufferOptions.setBufferSize(100);
                    disconnectedBufferOptions.setPersistBuffer(false);
                    disconnectedBufferOptions.setDeleteOldestMessages(false);
                    mqttAndroidClient.setBufferOpts(disconnectedBufferOptions);
                    subscribeToTopic();
                }
                @Override
                 public void onFailure(IMqttToken asyncActionToken, Throwable exception) {
                    Log.w("Mqtt", "Failed to connect to: " + serverUri + exception.toString());
                }
            });
        } catch (MqttException ex){
            ex.printStackTrace();
        }
    }

    private void subscribeToTopic() {
        try {
            mqttAndroidClient.subscribe(subscriptionTopic, 0, null, new IMqttActionListener() {
                @Override                
                public void onSuccess(IMqttToken asyncActionToken) {
                    Log.w("Mqtt","Subscribed!");
                }
                @Override                
                public void onFailure(IMqttToken asyncActionToken, Throwable exception) {
                    Log.w("Mqtt", "Subscribed fail!");
                }
            });

        } catch (MqttException ex) {
            System.err.println("Exception whilst subscribing");
            ex.printStackTrace();
        }
    }
    public void publishMessage(String msg)
            throws MqttException, UnsupportedEncodingException {
        byte[] encodedPayload = new byte[0];
        encodedPayload = msg.getBytes("UTF-8");
        MqttMessage message = new MqttMessage(encodedPayload);
        message.setId(5866);
        message.setRetained(true);
        message.setQos(0);
        mqttAndroidClient.publish("PUB", message);
    }
}



Comments

Post a Comment