Difference between revisions of "MQTT: Android Client Example"

From OnnoWiki
Jump to navigation Jump to search
(Created page with " It also contain one textView that will subscribe and show the message received from the MQTT service. * When click button Publish, you will see the “the payload” in the...")
 
 
(One intermediate revision by the same user not shown)
Line 1: Line 1:
 +
==settings.gradle==
  
It also contain one textView that will subscribe and show the message received from the MQTT service.
+
pluginManagement {
 +
    repositories {
 +
        gradlePluginPortal()
 +
        google()
 +
        mavenCentral()
 +
        maven {
 +
            url "https://repo.eclipse.org/content/repositories/paho-releases/"
 +
        }
 +
    }
 +
}
 +
dependencyResolutionManagement {
 +
    repositoriesMode.set(RepositoriesMode.FAIL_ON_PROJECT_REPOS)
 +
    repositories {
 +
        google()
 +
        mavenCentral()
 +
        maven {
 +
            url "https://repo.eclipse.org/content/repositories/paho-releases/"
 +
        }
 +
    }
 +
}
 +
rootProject.name = "ITTSPahoMQTT"
 +
include ':app'
  
* When click button Publish, you will see the “the payload” in the Messages bar. The message is already embedded in the coding.
 
* When click Publish from MQTT websocket client with correct topic (“event”), you will see the “YEAHH!!!” on you mobile app.
 
  
  
 +
==build.gradle :app==
  
Step 1: Add dependencies into gradle file.
 
Add Paho Android Service as a dependency to your app add the following parts to your gradle file.
 
 
repositories {
 
    maven {
 
        url "https://repo.eclipse.org/content/repositories/paho-releases/"
 
    }
 
}
 
 
dependencies {
 
    implementation fileTree(dir: 'libs', include: ['*.jar']) 
 
 
    implementation 'androidx.appcompat:appcompat:1.1.0'
 
    implementation 'androidx.constraintlayout:constraintlayout:1.1.3'
 
    testImplementation 'junit:junit:4.12'
 
    androidTestImplementation 'androidx.test.ext:junit:1.1.1'
 
    androidTestImplementation 'androidx.test.espresso:espresso-core:3.2.0'
 
  
 +
dependencies {
 +
    .....
 
     implementation('org.eclipse.paho:org.eclipse.paho.android.service:1.0.2') {
 
     implementation('org.eclipse.paho:org.eclipse.paho.android.service:1.0.2') {
 
         exclude module: 'support-v4'
 
         exclude module: 'support-v4'
 
     }
 
     }
 
 
     implementation 'androidx.localbroadcastmanager:localbroadcastmanager:1.0.0'
 
     implementation 'androidx.localbroadcastmanager:localbroadcastmanager:1.0.0'
 
  }
 
  }
Line 34: Line 39:
  
  
Step 2: Add permission on AndroidManifest.xml
 
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 <application> tag:
 
  
<service android:name="org.eclipse.paho.android.service.MqttService" >
+
==AndroidManifest.xml==
</service>
 
  
The Paho Android Service needs the following permissions to work:
 
  
  <uses-permission android:name="android.permission.WAKE_LOCK" />
+
  <?xml version="1.0" encoding="utf-8"?>
<uses-permission android:name="android.permission.INTERNET" />
+
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
+
    package="itts.onno.ittspahomqtt">
<uses-permission android:name="android.permission.READ_PHONE_STATE" />
+
 +
    <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" />
 +
 +
    <application
 +
        .....     
 +
        <service android:name="org.eclipse.paho.android.service.MqttService" >
 +
        </service>
 +
    </application>
 +
</manifest>
  
  
 
+
==activity_main.xml==
Step 3: Design the layout activity_main.xml
 
Update your layout.
 
 
 
  
 
  <?xml version="1.0" encoding="utf-8"?>
 
  <?xml version="1.0" encoding="utf-8"?>
Line 93: Line 102:
 
         app:layout_constraintHorizontal_bias="0.201"
 
         app:layout_constraintHorizontal_bias="0.201"
 
         app:layout_constraintStart_toStartOf="parent"
 
         app:layout_constraintStart_toStartOf="parent"
         app:layout_constraintTop_toTopOf="parent" />
+
         app:layout_constraintTop_toTopOf="parent" />  
 
   
 
   
 
     <Button
 
     <Button
Line 105: Line 114:
 
         app:layout_constraintHorizontal_bias="0.78"
 
         app:layout_constraintHorizontal_bias="0.78"
 
         app:layout_constraintStart_toStartOf="parent"
 
         app:layout_constraintStart_toStartOf="parent"
         app:layout_constraintTop_toTopOf="parent" />  
+
         app:layout_constraintTop_toTopOf="parent" />
 
   
 
   
 
  </androidx.constraintlayout.widget.ConstraintLayout>
 
  </androidx.constraintlayout.widget.ConstraintLayout>
Line 111: Line 120:
  
  
 +
==MainActivity.java==
  
  
Step 4: Write the code in MainActivity.java
+
  package itts.onno.ittspahomqtt;
Write the coding below at MainActivity.java.
 
If you have the MQTT service in your computer like mosquitto service with port 1883, you can uncomment the line below:
 
//client = new MqttAndroidClient(this.getApplicationContext(), “tcp://192.168.43.41:1883”,clientId);
 
 
 
Picture of MainActivity.java:
 
 
 
 
 
 
 
 
 
 
 
 
 
 
  package com.example.subcribe_java;
 
 
import androidx.appcompat.app.AppCompatActivity;  
 
 
   
 
   
 +
import androidx.appcompat.app.AppCompatActivity;
 
  import android.os.Bundle;
 
  import android.os.Bundle;
 
  import android.view.View;
 
  import android.view.View;
Line 147: Line 143:
 
   
 
   
 
     MqttAndroidClient client;
 
     MqttAndroidClient client;
     TextView subText;
+
     TextView subText;  
 
   
 
   
 
     @Override
 
     @Override
 
     protected void onCreate(Bundle savedInstanceState) {
 
     protected void onCreate(Bundle savedInstanceState) {
 
         super.onCreate(savedInstanceState);
 
         super.onCreate(savedInstanceState);
         setContentView(R.layout.activity_main);
+
         setContentView(R.layout.activity_main);  
 
   
 
   
 
         subText = (TextView)findViewById(R.id.subText);
 
         subText = (TextView)findViewById(R.id.subText);
 
   
 
   
 
         String clientId = MqttClient.generateClientId();
 
         String clientId = MqttClient.generateClientId();
         client = new MqttAndroidClient(this.getApplicationContext(), "tcp://broker.mqttdashboard.com:1883",clientId);
+
         // client = new MqttAndroidClient(this.getApplicationContext(), "tcp://broker.mqttdashboard.com:1883",clientId);
         //client = new MqttAndroidClient(this.getApplicationContext(), "tcp://192.168.43.41:1883",clientId);
+
         client = new MqttAndroidClient(this.getApplicationContext(), "tcp://192.168.0.111:1883",clientId);
   
+
 
 +
  //* -------------- masalah membuat aplikasi crash ------------------------
 
         try {
 
         try {
 
             IMqttToken token = client.connect();
 
             IMqttToken token = client.connect();
Line 166: Line 163:
 
                 public void onSuccess(IMqttToken asyncActionToken) {
 
                 public void onSuccess(IMqttToken asyncActionToken) {
 
                     Toast.makeText(MainActivity.this,"connected!!",Toast.LENGTH_LONG).show();
 
                     Toast.makeText(MainActivity.this,"connected!!",Toast.LENGTH_LONG).show();
                     setSubscription();  
+
                     setSubscription();
 +
                }
 
   
 
   
                }
 
 
 
                 @Override
 
                 @Override
 
                 public void onFailure(IMqttToken asyncActionToken, Throwable exception) {
 
                 public void onFailure(IMqttToken asyncActionToken, Throwable exception) {
Line 175: Line 171:
 
                 }
 
                 }
 
             });
 
             });
          } catch (MqttException e) {
+
        } catch (MqttException e) {
              e.printStackTrace();
+
            e.printStackTrace();
         }  
+
         }
   
+
 
 +
  //* ---------------------------------------------------------------------------
 +
 
 +
 
 +
 
 +
 
 
         client.setCallback(new MqttCallback() {
 
         client.setCallback(new MqttCallback() {
 
             @Override
 
             @Override
             public void connectionLost(Throwable cause) {  
+
             public void connectionLost(Throwable cause) {
 
             }
 
             }
 
 
             @Override
 
             @Override
 
             public void messageArrived(String topic, MqttMessage message) throws Exception {
 
             public void messageArrived(String topic, MqttMessage message) throws Exception {
 
                 subText.setText(new String(message.getPayload()));
 
                 subText.setText(new String(message.getPayload()));
             }  
+
             }
 +
            @Override
 +
            public void deliveryComplete(IMqttDeliveryToken token) {
 +
            }
 +
        });
 +
    }
 
   
 
   
            @Override
 
            public void deliveryComplete(IMqttDeliveryToken token) {
 
 
            }
 
        });
 
 
    }
 
 
    public void published(View v){
 
 
        String topic = "event";
 
        String message = "the payload";
 
        try {
 
            client.publish(topic, message.getBytes(),0,false);
 
            Toast.makeText(this,"Published Message",Toast.LENGTH_SHORT).show();
 
        } catch ( MqttException e) {
 
            e.printStackTrace();
 
        }
 
    }
 
 
    private void setSubscription(){
 
 
        try{
 
 
            client.subscribe("event",0);
 
 
 
        }catch (MqttException e){
 
            e.printStackTrace();
 
        }
 
    }
 
 
    public void conn(View v){
 
 
        try {
 
            IMqttToken token = client.connect();
 
            token.setActionCallback(new IMqttActionListener() {
 
                @Override
 
                public void onSuccess(IMqttToken asyncActionToken) {
 
                    Toast.makeText(MainActivity.this,"connected!!",Toast.LENGTH_LONG).show();
 
                    setSubscription();
 
 
                }
 
 
                @Override
 
                public void onFailure(IMqttToken asyncActionToken, Throwable exception) {
 
                    Toast.makeText(MainActivity.this,"connection failed!!",Toast.LENGTH_LONG).show();
 
                }
 
            });
 
        } catch (MqttException e) {
 
            e.printStackTrace();
 
        }
 
 
    }
 
 
    public void disconn(View v){
 
 
        try {
 
            IMqttToken token = client.disconnect();
 
            token.setActionCallback(new IMqttActionListener() {
 
                @Override
 
                public void onSuccess(IMqttToken asyncActionToken) {
 
                    Toast.makeText(MainActivity.this,"Disconnected!!",Toast.LENGTH_LONG).show();
 
 
 
                }
 
 
                @Override
 
                public void onFailure(IMqttToken asyncActionToken, Throwable exception) {
 
                    Toast.makeText(MainActivity.this,"Could not diconnect!!",Toast.LENGTH_LONG).show();
 
                }
 
            });
 
        } catch (MqttException e) {
 
            e.printStackTrace();
 
        }
 
    }
 
 
}
 
 
 
 
Step 5: You can test you mobile app
 
 
RUN the app
 
In browser, open the MQTT websocket client as link below:
 
http://www.hivemq.com/demos/websocket-client/
 
 
   
 
   
  Click button connect and Add New Topic Subcription.
+
    public void published(View v){
 
+
   
 +
        String topic = "event";
 +
        String message = "the payload";
 +
        try {
 +
            client.publish(topic, message.getBytes(),0,false);
 +
            Toast.makeText(this,"Published Message",Toast.LENGTH_SHORT).show();
 +
        } catch ( MqttException e) {
 +
            e.printStackTrace();
 +
        }
 +
    }
 
   
 
   
Example of Topic in my program:
+
    private void setSubscription(){
 +
        try{
 +
            client.subscribe("event",0);
 +
        }catch (MqttException e){
 +
            e.printStackTrace();
 +
        }
 +
    }
 
   
 
   
event
+
    public void conn(View v){
QoS = 0
+
        try {
 
+
            IMqttToken token = client.connect();
 +
            token.setActionCallback(new IMqttActionListener() {
 +
                @Override
 +
                public void onSuccess(IMqttToken asyncActionToken) {
 +
                    Toast.makeText(MainActivity.this,"connected!!",Toast.LENGTH_LONG).show();
 +
                    setSubscription();
 +
                }
 +
                @Override
 +
                public void onFailure(IMqttToken asyncActionToken, Throwable exception) {
 +
                    Toast.makeText(MainActivity.this,"connection failed!!",Toast.LENGTH_LONG).show();
 +
                }
 +
            });
 +
        } catch (MqttException e) {
 +
            e.printStackTrace();
 +
        }
 +
    }
 
   
 
   
Click subscribe.
+
    public void disconn(View v){
When click button Publish, you will see the “the payload” in the Messages bar. The message is already embedded in the coding.
+
          try {
When click Publish from MQTT websocket client with correct topic (“event”), you will see the “YEAHH!!!” on you mobile app.
+
            IMqttToken token = client.disconnect();
 
+
            token.setActionCallback(new IMqttActionListener() {
 +
                @Override
 +
                public void onSuccess(IMqttToken asyncActionToken) {
 +
                    Toast.makeText(MainActivity.this,"Disconnected!!",Toast.LENGTH_LONG).show();
 +
                }
 +
                @Override
 +
                public void onFailure(IMqttToken asyncActionToken, Throwable exception) {
 +
                    Toast.makeText(MainActivity.this,"Could not diconnect!!",Toast.LENGTH_LONG).show();
 +
                }
 +
            });
 +
        } catch (MqttException e) {
 +
            e.printStackTrace();
 +
        }
 +
    }
 +
}
  
 
==Referensi==
 
==Referensi==
  
 
* https://people.utm.my/shaharil/mqtt-android-studio/
 
* https://people.utm.my/shaharil/mqtt-android-studio/

Latest revision as of 10:56, 4 April 2022

settings.gradle

pluginManagement {
    repositories {
        gradlePluginPortal()
        google()
        mavenCentral()
        maven {
            url "https://repo.eclipse.org/content/repositories/paho-releases/"
        }
    }
}
dependencyResolutionManagement {
    repositoriesMode.set(RepositoriesMode.FAIL_ON_PROJECT_REPOS)
    repositories {
        google()
        mavenCentral()
        maven {
            url "https://repo.eclipse.org/content/repositories/paho-releases/"
        }
    }
}
rootProject.name = "ITTSPahoMQTT"
include ':app'


build.gradle :app

dependencies { 
    .....
    implementation('org.eclipse.paho:org.eclipse.paho.android.service:1.0.2') {
        exclude module: 'support-v4'
    }
    implementation 'androidx.localbroadcastmanager:localbroadcastmanager:1.0.0'
}



AndroidManifest.xml

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="itts.onno.ittspahomqtt">

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

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


activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout 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">

    <Button
        android:id="@+id/button"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginTop="236dp"
        android:onClick="published"
        android:text="PUBLISH"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintHorizontal_bias="0.498"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent" /> 

    <TextView
        android:id="@+id/subText"
        android:layout_width="141dp"
        android:layout_height="68dp"
        android:layout_marginTop="360dp"
        android:text="TextView"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent" /> 

    <Button
        android:id="@+id/connBtn"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginTop="524dp"
        android:onClick="conn"
        android:text="connect"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintHorizontal_bias="0.201"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent" /> 

    <Button
        android:id="@+id/disconnBtn"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginTop="524dp"
        android:onClick="disconn"
        android:text="disconnect"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintHorizontal_bias="0.78"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

</androidx.constraintlayout.widget.ConstraintLayout>


MainActivity.java

package itts.onno.ittspahomqtt;

import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.TextView;
import android.widget.Toast;

import org.eclipse.paho.android.service.MqttAndroidClient;
import org.eclipse.paho.client.mqttv3.IMqttActionListener;
import org.eclipse.paho.client.mqttv3.IMqttDeliveryToken;
import org.eclipse.paho.client.mqttv3.IMqttToken;
import org.eclipse.paho.client.mqttv3.MqttCallback;
import org.eclipse.paho.client.mqttv3.MqttClient;
import org.eclipse.paho.client.mqttv3.MqttException;
import org.eclipse.paho.client.mqttv3.MqttMessage;

public class MainActivity extends AppCompatActivity {

    MqttAndroidClient client;
    TextView subText; 

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main); 

        subText = (TextView)findViewById(R.id.subText);

        String clientId = MqttClient.generateClientId();
        // client = new MqttAndroidClient(this.getApplicationContext(), "tcp://broker.mqttdashboard.com:1883",clientId);
        client = new MqttAndroidClient(this.getApplicationContext(), "tcp://192.168.0.111:1883",clientId);
//* -------------- masalah membuat aplikasi crash ------------------------
        try {
            IMqttToken token = client.connect();
            token.setActionCallback(new IMqttActionListener() {
                @Override
                public void onSuccess(IMqttToken asyncActionToken) {
                    Toast.makeText(MainActivity.this,"connected!!",Toast.LENGTH_LONG).show();
                    setSubscription();
               }

                @Override
                public void onFailure(IMqttToken asyncActionToken, Throwable exception) {
                    Toast.makeText(MainActivity.this,"connection failed!!",Toast.LENGTH_LONG).show();
                }
            });
        } catch (MqttException e) {
            e.printStackTrace();
        }
//* ---------------------------------------------------------------------------



        client.setCallback(new MqttCallback() {
            @Override
            public void connectionLost(Throwable cause) {
            }
            @Override
            public void messageArrived(String topic, MqttMessage message) throws Exception {
                subText.setText(new String(message.getPayload()));
            }
            @Override
            public void deliveryComplete(IMqttDeliveryToken token) {
            }
        });
    }


    public void published(View v){

        String topic = "event";
        String message = "the payload";
        try {
            client.publish(topic, message.getBytes(),0,false);
            Toast.makeText(this,"Published Message",Toast.LENGTH_SHORT).show();
        } catch ( MqttException e) {
            e.printStackTrace();
        }
    } 

    private void setSubscription(){ 
        try{
            client.subscribe("event",0);
        }catch (MqttException e){
            e.printStackTrace();
        }
    }

    public void conn(View v){
        try {
            IMqttToken token = client.connect();
            token.setActionCallback(new IMqttActionListener() {
                @Override
                public void onSuccess(IMqttToken asyncActionToken) {
                    Toast.makeText(MainActivity.this,"connected!!",Toast.LENGTH_LONG).show();
                    setSubscription(); 
                }
                @Override
                public void onFailure(IMqttToken asyncActionToken, Throwable exception) {
                    Toast.makeText(MainActivity.this,"connection failed!!",Toast.LENGTH_LONG).show();
                }
            });
        } catch (MqttException e) {
            e.printStackTrace();
        }
    }

    public void disconn(View v){
         try {
            IMqttToken token = client.disconnect();
            token.setActionCallback(new IMqttActionListener() {
                @Override
                public void onSuccess(IMqttToken asyncActionToken) {
                    Toast.makeText(MainActivity.this,"Disconnected!!",Toast.LENGTH_LONG).show();
                }
                @Override
                public void onFailure(IMqttToken asyncActionToken, Throwable exception) {
                    Toast.makeText(MainActivity.this,"Could not diconnect!!",Toast.LENGTH_LONG).show();
                }
            });
        } catch (MqttException e) {
            e.printStackTrace();
        }
    }
}

Referensi