Android Studio - MQTT not connecting

android studio mqtt client tutorial
android mqtt broker
paho mqtt ssl example android
mqtt android kotlin
mosquitto
android mqtt background service
android mqtt subscribe
mqtt client app android

I have just started learning using MQTT protocol with Android Studio. Using mosquitto broker, I am able to exchange messages between pub/sub windows. But when I send message to broker through android studio, the app builds successfully but nothing displays on broker's end & system prints Connection Failure. The same code works fine on eclipse java application, but not working on android although required libraries and dependencies have been added.

Please help, what am I missing in this basic step so i can learn forward. Thank you!

app-build.gradle

    dependencies {
    compile fileTree(dir: 'libs', include: ['*.jar'])
    androidTestCompile('com.android.support.test.espresso:espresso-core:2.2.2', {
        exclude group: 'com.android.support', module: 'support-annotations'
    })
    compile 'com.android.support:appcompat-v7:25.2.0'
    compile 'com.android.support.constraint:constraint-layout:1.0.2'
    testCompile 'junit:junit:4.12'

// have added following dependencies

    provided 'com.google.android.things:androidthings:0.2-devpreview'
    provided 'com.google.android.things:androidthings:0.1-devpreview'
    compile 'org.eclipse.paho:org.eclipse.paho.client.mqttv3:1.0.2'

}

project-build.gradle

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

AndroidManifest.xml

 <manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.zoha.mqttandroidiot">

    <!-- Permissions the Application Requires -->
    <uses-permission android:name="android.permission.WAKE_LOCK" />
    <uses-permission android:name="android.permission.INTERNET" />
    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
    <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
    <uses-permission android:name="android.permission.READ_PHONE_STATE" />
    <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />


    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:roundIcon="@mipmap/ic_launcher_round"
        android:supportsRtl="true"
        android:theme="@style/AppTheme">


        <activity android:name=".HomeActivity">

            <intent-filter>
                <action android:name="android.intent.action.MAIN"/>
                <category android:name="android.intent.category.LAUNCHER"/>
            </intent-filter>

            <!-- Launch activity automatically on boot -->
            <intent-filter>
                <action android:name="android.intent.action.MAIN"/>
                <category android:name="android.intent.category.IOT_LAUNCHER"/>
                <category android:name="android.intent.category.DEFAULT"/>
            </intent-filter>

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

    </application>

</manifest>

HomeActivity

  public class HomeActivity extends AppCompatActivity{

    MqttAndroidClient client;
   // private static final MemoryPersistence persistence = new MemoryPersistence();

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

        final MqttAndroidClient mqttAndroidClient = new MqttAndroidClient(this.getApplicationContext(), "tcp://localhost:1883", "androidSampleClient");
        mqttAndroidClient.setCallback(new MqttCallback() {
            @Override
            public void connectionLost(Throwable cause) {
                System.out.println("Connection was lost!");

            }

            @Override
            public void messageArrived(String topic, MqttMessage message) throws Exception {
                System.out.println("Message Arrived!: " + topic + ": " + new String(message.getPayload()));

            }

            @Override
            public void deliveryComplete(IMqttDeliveryToken token) {
                System.out.println("Delivery Complete!");
            }
        });

        try {
            mqttAndroidClient.connect(null, new IMqttActionListener() {
                @Override
                public void onSuccess(IMqttToken asyncActionToken) {
                    System.out.println("Connection Success!");
                    try {
                        System.out.println("Subscribing to /test");
                        mqttAndroidClient.subscribe("/test", 0);
                        System.out.println("Subscribed to /test");
                        System.out.println("Publishing message..");
                        mqttAndroidClient.publish("/test", new MqttMessage("Hello world testing..!".getBytes()));
                    } catch (MqttException ex) {

                    }

                }

                @Override
                public void onFailure(IMqttToken asyncActionToken, Throwable exception) {
                    System.out.println("Connection Failure!");
                }
            });
        } catch (MqttException ex) {

        }


    }
    }

Ok so you need two libraries to use MQTT in Android. One is the mqtt paho client and other being Android service library.

compile 'org.eclipse.paho:org.eclipse.paho.android.service:1.0.2'
compile 'org.eclipse.paho:org.eclipse.paho.client.mqttv3:1.0.2'

Then, use MqttAndroidClient instead of MqttClient.

So do new MqttAndroidClient(...).

I posted a full Android MQTT service example here, if that helps.

EDIT: full activity example

(1) MemoryPersistence added when creating new MqttAndroidClient. (2) Two parameters added to .connect() method of the MqttAndroidClient (mqttConnectOptions and null). (3) Also, printing the error on onFailure()

public class HomeActivity extends AppCompatActivity {

    private MqttAndroidClient client;
    private final MemoryPersistence persistence = new MemoryPersistence();

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

        final MqttAndroidClient mqttAndroidClient = new MqttAndroidClient(this.getApplicationContext(), "tcp://localhost:1883", "androidSampleClient", persistence);
        mqttAndroidClient.setCallback(new MqttCallback() {
            @Override
            public void connectionLost(Throwable cause) {
                System.out.println("Connection was lost!");
            }

            @Override
            public void messageArrived(String topic, MqttMessage message) throws Exception {
                System.out.println("Message Arrived!: " + topic + ": " + new String(message.getPayload()));
            }

            @Override
            public void deliveryComplete(IMqttDeliveryToken token) {
                System.out.println("Delivery Complete!");
            }
        });

        MqttConnectOptions mqttConnectOptions = new MqttConnectOptions();
        mqttConnectOptions.setCleanSession(true);

        try {
            mqttAndroidClient.connect(mqttConnectOptions, null, new IMqttActionListener() {
                @Override
                public void onSuccess(IMqttToken asyncActionToken) {
                    System.out.println("Connection Success!");
                    try {
                        System.out.println("Subscribing to /test");
                        mqttAndroidClient.subscribe("/test", 0);
                        System.out.println("Subscribed to /test");
                        System.out.println("Publishing message..");
                        mqttAndroidClient.publish("/test", new MqttMessage("Hello world testing..!".getBytes()));
                    } catch (MqttException ex) {

                    }
                }

                @Override
                public void onFailure(IMqttToken asyncActionToken, Throwable exception) {
                    System.out.println("Connection Failure!");
                    System.out.println("throwable: " + exception.toString());
                }
            });
        } catch (MqttException ex) {
            System.out.println(ex.toString());
        }
    }
}

Paho Android Service - MQTT Client Library Encyclopedia, The MQTT connection is encapsulated within an Android-Service that runs in The most convenient way to start a new Android Application is to use Android Studio. The Paho Android Service is not meant to bind to directly. I hosted Mosquitto MQTT broker on Digital Ocean Cloud. Now, I am trying to connect it to the android studio. But it is not connecting to the MQTT broker.I tried with the following code.


MQTT protocol connection error, I have just started learning using MQTT protocol with Android Studio. fine on eclipse java application, but not working on android although  Here's all the information around the device: Organization ID: qi0pmu Device Type: iotdevice Device ID: 112233445566 Authentication Method: token Authentication Token: xxxxxxxxxx Here is the code around connecting using MqttAndroidClient. final private String CLIENT_IDENTIFIER = "d:qi0pmu:iotdevice:112233445566"; final private String USERNAME = "use-token-auth"; final private String PASSWORD


I had the same issue with MQTT publisher from an android device. While referring to tcp://localhost:1883 from an android emulator, I had to use http://10.0.2.2:1883 since emulator runs on its own VM and localhost would be emulators own loopback address.

MQTT Android Studio won't connect to my IoT application, I keep getting Connection Failure: Not authorized to connect when this function is run. It looks to me that everything is in order and I have been banging my head  Description. The Paho Android Service is an interface to the Paho Java MQTT Client library for the Android Platform. The MQTT connection is encapsulated within an Android-Service that runs in the background of the Android application, keeping it alive when the Android application is switching between different Activities.


I was getting Same Error but I have solved it. This is working code.

in gradle :

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 Manifest :

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

Service Tag inside Application:

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

Activity Code :

 MqttAndroidClient client;
 Button btnsub,btnpublish;

to connect with Mqtt client:

String clientId = MqttClient.generateClientId();
   client = new MqttAndroidClient(getApplicationContext(), "tcp://www.domain.in/ip:11883",clientId);
        client.connect().setActionCallback(new IMqttActionListener() {
            @Override
            public void onSuccess(IMqttToken asyncActionToken) {
                // We are connected
            }
            @Override
            public void onFailure(IMqttToken asyncActionToken, Throwable exception) {
            }
        });

To SubScribe on button click :

   client.subscribe("topic", 0, null, new IMqttActionListener() {
                        @Override
                        public void onSuccess(IMqttToken asyncActionToken) {
                        }
                        @Override
                        public void onFailure(IMqttToken asyncActionToken, Throwable exception) {
                        }
                    });
                    client.subscribe("topic", 0, new IMqttMessageListener() {
                        @Override
                        public void messageArrived(String topic, MqttMessage message) throws Exception {
                        }
                    });

to Publish on button click :

   MqttMessage message = new MqttMessage();
                    message.setPayload("message".getBytes());
                    client.publish("topic", message);

Getting started with the MQTT client for Java on Android, Import the sample app project from the MQTT SDK, in the path sdkroot \SDK\​clients\android\samples\mqttExerciser. The Problems view lists many build errors​. You  On this article, I will try to show you a little implementation of the MQTT protocol in Android based in my experience. MQTT Basics. As I previously mention, MQTT is a publish-subscribe-based messaging protocol, this means that clients must subscribe to a specific topic where messages are sent.


Issues · eclipse/paho.mqtt.android · GitHub, MQTT Android. Contribute to eclipse/paho.mqtt.android development by creating an account on GitHub. Installing Android Studio. This was as easy as a google search and file download. Use this link to install Android Studio on a PC with Windows 10 operating system. Install Android Studio. Creating the Project. After installing and opening Android Studio, create a new project (File->New->New Project… Enter a name for the project and click


How to Connect with MQTT on Android, Your browser does not currently recognize any of the video formats available. Click here to visit Duration: 6:20 Posted: Nov 11, 2017 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


Paho, Paho-MQTT is not able to connect more than 339 connections. Number of Visual Studio 2017 CrossCompile. Problems problems Android Studio with Paho. Mqtt technology is used as the communication protocol in the places where data is received from the sensors (such as smart home systems) where device communication is provided. For this project, we need to have these programs:-Android Studio-Python. 1. Dependecies. Create new app on Android Studio, then open build.gradle file and add these lines: