MQTT Client Library Encyclopedia – Paho Android Service

Guest post by Sandro Kock

Pahao Android Service
Language Java
License Eclipse Public License v1.0 and Eclipse Distribution License v1.0
API Style Asynchronous


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. This layer of abstraction is needed to be able to receive MQTT messages reliably. As the Paho Android Service is based on the Paho Java client library it can be considered stable and used in production. The project is actively maintained by the Eclipse Paho project.


MQTT 3.1 ok
MQTT 3.1.1 ok
LWT ok
Automatic Reconnect nok (On the road map)
QoS 0 ok
QoS 1 ok
QoS 2 ok
Authentication ok
Throttling nok



Android uses Gradle as a build system and dependency management, therefor this blog post describes how the Paho Android Service can be added to an application via Gradle. The most convenient way to start a new Android Application is to use Android Studio. To add the Paho Android Service as a dependency to you app add the following parts to your gradle file.

The first part adds the Paho release repository to the gradle config, so that Gradle is able to find the packaged Paho Android Service JAR. The second part adds the Paho Android Service as a dependency to the application. The exclusion of the Android Support library exclude module: 'support-v4' is only necessary if the Android application is using the Android Support Library to backport newer Android features to older Android versions. To have the latest Snapshot release within your application the gradle config below can be used.


As already mentioned, the Paho Android Service encapsulates the MQTT connection and offers an API for that. 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:

The Paho Android Service needs the following permissions to work:

Add those to the <manifest> tag.

Usually an Android Activity requests or binds to an Android Service to use it, for e.g. the LocationManager to receive updates when the GPS position of the user changes. The Paho Android Service is not meant to bind to directly. Instead the provided MqttAndroidClient client interface binds to the service once created. To create and establish an MQTT-connection use the following code snipped:

In the first line a helper Function of the Paho MQTT client is used to generate a random user id. The second line creates an instance of an Android MQTT client, that will bind to the Paho Android Service. 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. Running the above example inside an Android Activity.onCreate method will print “onSuccess” or “onFailure” to the console.

Connect with MQTT 3.1 or MQTT 3.1.1

The MqttAndroidClient will connect with MQTT 3.1.1 by default, with a fallback to 3.1. To intentionally connect with MQTT 3.1 a MqttConnectOptions object can be supplied to the connect method:

Connect with LWT

Like the MQTT version, the Last Will And Testament (LWT) can be added into the MqttConnectOptions object.

Besides the payload of the LWT, everything is straight forward and can be just set. Many MQTT clients assume that the payload is an UTF-8 formatted string and convert the payload automatically. The fact that MQTT is a binary protocol is often hidden with that. By calling String#getBytes the string will be encoded with the systems default charset (UTF-8 on Android).

Connect with Username / Password

Again like the MQTT version and the LWT, the username and password can be supplied within the options object.


The MqttAndroidClient allows messages to be published via its publish(topic, MqttMessage) method. By design the MqttAndroidClient dose not queue any messages if the client is not connected and will throw an error when trying to send messages when the client is offline client.isConnected() == false. After the first connect, the IMqttActionListener.onSuccess method is called when a MQTT connection is established successfully.

Publish a retained message

To send a retained MQTT message the MqttMessage.retained attribute can be set to true via MqttMessage.setRetained(true).


Subscriptions can be created via the MqttAndroidClient.subscribe method, which takes the topic and the QOS as parameters and returns a IMqttToken. The token can be used to keep track if the subscription can successfully established or failed. The example below subscribes to the topic “foo/bar” with QOS 1



To disconnect the client call the disconnect method of the MqttAndroidClient object. The example below saves the token returned by the disconnect method and adds a IMqttActionListener to get notified when the client is successfully disconnected.

Using SSL / TLS

When connecting with SSL/TLS the MQTT-broker has to use a valid certificate that is trusted via the chain of trust of the Android device or provide a custom Java SocketFactory. Currently I am not aware of any public MQTT broker that can be used to test a SSL/TLS connection without a custom SocketFactory, hopefully this will change in the near feature with Let’s Encrypt in place.

IoT Eclipse provides an MQTT Sandbox running MQTT encrypted on and supports TLS 1.0, 1.1 and 1.2. Android on the other hand uses a cryptography API library called BouncyCastle. To generate a BouncyCastle keystore (BKS) on a development machine the BounceCastleProvider class is required in the JAVA-Classpath. The JAR containing the class can be downloaded here. To generate the BKS the JDK keytool can be used with the following parameters:

The command assumes that you saved the BouncyCastle JAR and the into the current directory. It will generate a BouncyCastle Keystore names with the password set to eclipse-password.

To actually use the keystore, create a folder named “assets” in the “src/main” directory of you app and copy the file into it. The following example will create a secure MQTT connection to the Eclipse test broker:

The example uses the utility function getSSLSocketFactory of the MqttAndroidClient to create a custom SocketFactory from the BKS keystore input stream.

Full example application

The Eclipse Paho project provides a very detailed example application that demonstrates the capabilities of the Paho Android Service. A packaged application is available at Paho Android Sample. The APK is based on the current development branch in the Eclipse repository. To clone the entire GIT repository use the following command:

The Android sample application source is located in the folder, that can be opened with Android Studio.

Author Information

Sandro Kock
Since 2014 Sandro Kock is a mobile developer at SSV Software Systems, responsible for developing mobile solutions, with a focus on IoT/M2M. Before that he wrote the MQTT client MQTTlens, which is based on Polymer.


  1. Ian Gough says:

    It may be worth mentioning for those unfamiliar with the Paho Android Service that you need to call client.setCallback() and implement MqttCallback in order to receive messages on the topics to which you subscribed.

    1. Yes. I was also looking for that here.

      I’ve added my subscription logic on the onSuccess method block:
      public void onSuccess(IMqttToken asyncActionToken) {
      // We are connected
      Log.d(TAG, “onSuccess”);

      Works, but seems strange to chain events like this?

    2. xs says:

      How to reconnect?

    3. vivek kumar verma says:

      I am trapped in a situation where i am trying to set different textview(to display message) for different subscribed topic.
      i.e let i am subscribed to two different topic and i am getting different messages on that different topic and i need to display those different subscribed topic message to the different text view.
      plz help

    4. Muhammad Abrar Gurmani says:

      I am trying to enter a broker url from a text box
      actually i am hosting my own broker server on esp8266
      and its url is like tcp://
      now if i enter this whole string here
      MqttAndroidClient client =
      new MqttAndroidClient(this.getApplicationContext(), “tcp://”,
      it works but if want to enter this url from a text box it doesnt work
      help me please my final year project is at stake 😛

  2. viraj says:

    I tried executing the above steps in Android Studio, i also added jar files to libs even then i have the following errors:
    Error:(16, 27) error: cannot find symbol variable MqttClient
    Error:(18, 21) error: cannot find symbol class MqttAndroidClient
    Error:(17, 9) error: cannot find symbol class MqttAndroidClient
    Error:(22, 13) error: cannot find symbol class IMqttToken
    Error:(23, 41) error: cannot find symbol class IMqttActionListener
    please help!

    1. Hi Viraj,

      did you include the library? The errors does not seem to have anything to do with Paho itself, it seems that’s a dependency issue.

      All the best,
      Dominik from the HiveMQ Team

    2. thats because the example above is missing the second library in the dependencies directive of your gradle file
      compile(‘org.eclipse.paho:org.eclipse.paho.client.mqttv3:1.0.3-SNAPSHOT’) {
      exclude module: ‘support-v4’

    3. bytehala says:

      Hi viraj, were you able to solve the problem? It is indeed a dependency issue. Adding the jar files to libs is Step 1. After that, you need to make sure that the jars are included in the Build Path.

      Anyway, if you wanted to use Android Studio, please check out my github. The link is in one of the comments further down. Hope this helps.

  3. Dadan says:

    How to get message from a topic when I subscribe that topic ?

    1. Hi Dadan,

      you can set a MqttCallback via the setCallback method. You can find an example implementation of such a method here:

      Hope this helps,

  4. I keep running into issues with this lib. I’ve tried both 1.0.2 and 1.0.3 (Android Service) and it just does not seem to work and not stable.

    for instance, and following your example above, I tried to get a boolean value from asynctoken.getSessionPresent() and the code blows up at run-time with a null exception, but the token itself is not null.

    Here’s the code:

    token.setActionCallback(new IMqttActionListener() {
    public void onSuccess(IMqttToken asyncActionToken) {
    // We are connected
    Log.d(TAG, “onSuccess”);
    if(asyncActionToken == null){
    Log.d(TAG, “obj is null”);
    Log.d(TAG, “not null – issession present? ” + asyncActionToken.getSessionPresent());

  5. Kalpesh says:

    It works on my emulator but does not work on a device

    1. bytehala says:

      Hi Kalpesh, I just published the Android Studio version of the Paho Android sample client on my Github:

      I was able to create an app for a client using it, so hopefully it will work on your device. Let me know if it helps.

  6. moshe says:

    hey is anybody else getting a NullPointer Exception when subscribing?
    could use some help..

    1. Hi moshe,

      A NullPointerException is often a sign that something wasn’t initialized as expected. The best way to get help with that if you believe that is a Paho Bug would be to raise an issue with Paho or check if there is a known issue with a workaround available. The Paho Issue Tracker can be found here:

      Hope this helps,
      Dominik from the HiveMQ Team

  7. Dhanasekaran S says:

    It work for me

  8. Yasir says:

    Thank you for the fantastic tutorial, I was wondering if you could let me know how I can view the messages of the topic I have subscribed to? The way I have implemented it is that you press a button and it subscribes but I want to extend it so that it subscribes to the topic then displays the message.

  9. prakash says:

    how to get All Connected Client ID so that i can publish Message to all the connected client without subscribe.

    1. Hi Prakash,

      MQTT is designed as a publish/subscribe protocol and thus direct communication between clients is not possible without using subscription mechanisms. You can learn more about that in this blog post:

      If you want to get all client identifiers you can use the plugin system of HiveMQ for that. Take a look at the ClientService:

      Hope this helps,
      Dominik from the HiveMQ Team

  10. Andrea says:

    I managed to publish and subscribe but I really can’t understand how to listed for subscription message.

  11. Tal says:

    Thank you very much for this great tutorial!
    but, there is a problem cloning the Git repository of the example..
    I’ll be grateful if it would be fixed, since I have to see an example of the ‘gradle’ part.
    my project’s gradle doesn’t compile at all when i add the needed lines..
    Thank you in advance..!

  12. Frogec says:

    great tutorials and explanations on this website! Very well written and with a lot of nice examples.

    Thank you!

  13. Cuong Nguyen says:

    My project has been working well by following the first way to install paho (the stable version: service:1.0.2). However, when I use the second way (using snapshot), it shows that the following cannot be imported:

    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;

    1. Hi Cuong,

      Thanks for your comment.
      I would recommend to ask this question on the paho dev mailing list:

      Best regards,
      Christian from the HiveMQ Team

  14. Manish Prajapat says:

    Thank you so much .Worked smoothly

  15. Fabricio says:

    As I could handle the reconnection, I tried to disconnect and connect when the network goes and return respectively but when I connect I have a listener but I get two or n times the same message

  16. Morteza says:

    I’m using OpenHab and my topic (or my command) is like this: “/home/1/ard1/p1/com:command:on:1”. How can I convert this command here? Thanks.

  17. mohamed says:


    Haw i can receive messages when app is closed. when the application is closed by user the mqtt service is also destroyed beacause it run in the same process.
    I would like the mqtt service still running in background and bounded to a singleton mqtt android client in Application class. to continue receive message from mqtt broker in background and show notification to user to ropen application
    on click.


  18. rushabh says:

    Hey i dont have a username and password for HiveMq broker,so i wrote any random username and password and i published a topic(hello),now at reciever side i have mosquitto broker who is subscribed to same topic (hello),i am not able to recieve the topic,whats wrong?
    what is mqtthost?,i have put mqtthost as


    and topic as

    String topicstr=”hello/ro”;
    where i am going wrong?

    1. Hallo,

      glad to see you’re taking an interest in the MQTT protocol.
      When using our public broker (tcp:// there is no need for either username or password.

      Florian, from the HiveMQ Team.

  19. Krunal Bhavsar says:

    Thanks for good note on how to use mqtt in android. I tried the tutorial but stuck. As per section of connection, where it uses client.connect and then uses onSuccess, it does not put log in my console. Also when I try to publish and try it in my mobile, it throws nullpoint exception. When I tried to use client.isConnected(), I found that it is not connected.

    Could you possibly know why client.connect does not connect ? I tried tcp:// from MQTTlens and I was able to connect hence looks like no issue with firewall.


    1. siaa_98 says:

      because it connect to the server in asynchronous way, so you should put subscribe method inside onSuccess method of IMqttActionListener not just after connect

  20. Hi,

    I am not getting onSuccess or onFailure message while using below code under onCreate. Could you please help ?

    String clientId = MqttClient.generateClientId();
    MqttAndroidClient client =
    new MqttAndroidClient(this.getApplicationContext(), “tcp://”,

    try {
    IMqttToken token = client.connect();
    token.setActionCallback(new IMqttActionListener() {
    public void onSuccess(IMqttToken asyncActionToken) {
    // We are connected
    Log.d(TAG, “onSuccess”);

    public void onFailure(IMqttToken asyncActionToken, Throwable exception) {
    // Something went wrong e.g. connection timeout or firewall problems
    Log.d(TAG, “onFailure”);

    } catch (MqttException e) {

    1. Raj Kumar Singh says:

      I had the sameissue, I fixed it by putting these lines inside Application tag in the manifest file.

      service android name=

      You might have kept it outside the applicatrion Tag

  21. Godfrey says:

    Hi Sandro, is there a way to provide the virtual host when connecting to a broker?
    My requirement is to connect to a vhost.

    My configuration example is:
    broker: tcp://
    username: myuser
    password: myuser
    VHost: MyVHost

    I am able to successfully connect to the broker using the credentials (username, password) but i didnt get a way to provide the VHost.
    Please help.

  22. denisov says:

    NullPinterException when try to subscribe…. 🙁

    1. Hi denisov,

      A NullPointerException is often a sign that something wasn’t initialized as expected. The best way to get help with that if you believe that is a Paho Bug would be to raise an issue with Paho or check if there is a known issue with a workaround available. The Paho Issue Tracker can be found here:

      Hope this helps,
      Florian from the HiveMQ Team

  23. Claudio Calazans says:

    When I synch the gradle the only library that appears on my list is:

    The org.eclipse.paho.client.MQTTv3.1.0.2, doesn’t.

    Can someone help me to understand if I missed something or if its an updated version?

    1. Hi Claudio,

      Did you use the correct maven repository ?

      Be aware that there are two different ones.
      One ends with …/paho-releases/
      the other one with …/paho-snapshots/

      Hope that helps,
      The HiveMQ Team

  24. Sarah says:

    How can I run hiveMQ locally to see published messages sent from ‘paho’ client

    1. Hi Sarah,

      Please see the installation guide for the HiveMQ broker.

      Kind regards,
      Florian from The HiveMQ Team.

  25. Sthor69 says:

    I tried with your code (with the 1.0.2 release of paho service) but I get a NullPointerException in the publish method.
    In particular, in, at line 812 where there is the call to mqttService.publish(…), mqttService is null.

    What could be the reason?


  26. Tai says:

    Please help me.
    Read data at message from mqtt to listview on android studio.

  27. Lucas says:

    Extremely helpful, thanks!

  28. ashu says:


    im new to android development could someone please help me with below code. i want to make if statement from the mqtt payload . how can i make playload = connected then show it is Textview

    public void messageArrived(String topic, MqttMessage message) throws Exception {
    subText.setText(new String(message.getPayload()));
    // Vibrator.vibrate(500);

  29. Aravindh Samidurai says:

    It’s working fine for me thank you developer but, i have some doubts about MQTT.
    1. What is message limit or daily quota in free account.
    2. How to create personal account.
    3. Is it possible to receive messages when app is background state.


  30. Abhishek joshi says:

    package com.example.techasia.secureasia;

    import android.os.Bundle;
    import android.view.View;
    import android.widget.TextView;
    import android.widget.Toast;

    import org.eclipse.paho.client.mqttv3.IMqttActionListener;
    import org.eclipse.paho.client.mqttv3.IMqttToken;
    import org.eclipse.paho.client.mqttv3.MqttClient;
    import org.eclipse.paho.client.mqttv3.MqttConnectOptions;
    import org.eclipse.paho.client.mqttv3.MqttException;

    public class MainActivity extends AppCompatActivity {
    MqttAndroidClient client;

    protected void onCreate(Bundle savedInstanceState) {

    String clientId = MqttClient.generateClientId();
    client = new MqttAndroidClient(this.getApplicationContext(), “″,

    try {
    IMqttToken token = client.connect();
    token.setActionCallback(new IMqttActionListener() {
    public void onSuccess(IMqttToken asyncActionToken) {

    public void onFailure(IMqttToken asyncActionToken, Throwable exception) {
    Toast.makeText(MainActivity.this,”connection failed!!”,Toast.LENGTH_LONG).show();
    } catch (MqttException e) {

    public void pub(View v){
    String topic = “event”;
    String message = “the payload”;
    try {
    client.publish(topic, message.getBytes(),0,false);
    } catch ( MqttException e) {


    Its not connecting to the server..i have my own mqtt server but its not connecting plz help.

  31. Abhishek says:

    I want a help for just making an android app as publisher and subscriber as a linux terminal. How can I proceed further.

    1. Hi Abhishek,

      Nice to see you’re taking an interest in MQTT and HiveMQ.
      What kind of information is it, that you are looking for and don’t seem to be able to find?

      Kind regards,
      Florian from The HiveMQ Team.

  32. Gilberto says:

    Hi , I get this error Unrecognized packet (32108) .., what exactly am I supposed to look on this , kindly help

  33. Just me says:

    Hello, i want to ask:
    1) what broker did u use?
    2) i connect using tcp protocol 1883 port on paho, but i receive network error, i think that’s caused by my broker, that using mqtt protocol 1883 port

    1. Hi there,

      the Paho Android Service Client uses the public HiveMQ Broker ( for test purposes.

      Of course you can also use a broker that is running on one of your own devices. But don’t forget that you need to open the port 1883 on the machine that is running the broker. That is probably the reason why you receive a network error.

      Hope this helps,
      Abdullah from the HiveMQ Team.

  34. meryem says:

    Hi there,
    I want to use JobScheduler on Mqtt, because i have a problem in Background service. It’s possible ?
    Thank you

    1. Hi Meryem,

      can you explain to me what kind of problem you have in the background service?

      In principle it should also work with a job scheduler.

      Kind regards,
      Abdullah from the HiveMQ Team

  35. meryem says:

    I want to use MQTT for Version Oreo (long Running in Background) ! I m trying one version of Mqtt with Job scheduler.

    Kind regards,

  36. nur says:

    hi, how to use this by using ip address instead?

    1. Hi Nur,

      Nice to see you’re taking an interest in MQTT and HiveMQ.

      You can use this and all the other client libraries with an ip address.

      For this client library you need to change the following line in the given code-snippet:

      MqttAndroidClient client = new MqttAndroidClient(this.getApplicationContext(), "tcp://", clientId)

      Hope I could help.

      Kind regards,
      Abdullah from the HiveMQ Team

  37. Ulrich says:


    I am trying to use this method to connect to Adafruit IO. I am new to this and do not understand what I need to change in the code to complete this task, any help would be much appreciated.

Leave a Reply

Your email address will not be published. Required fields are marked *