JavaEar 专注于收集分享传播有价值的技术资料

Having trouble connecting android with MQTT to broker

I am trying to connect to an Apollo broker, this code works perfectly when I use it alone in a normal java project, everything is exactly the the same except now its in an android project and i try to run it when i click a button from MainActivity.

I have a text box that gets updated to "1" before i try to connect MQttClient however the second .setT("2") does not get run so I think the problem is with client.connect(opts) as if i just do client.connect() the text box gets updated to "2" but since i need the username and password it from opts the rest does not run

Just started using MQTT learning as I go along. Thanks for any help.

package com.example.androidmqtt;

import org.eclipse.paho.client.mqttv3.MqttClient;
import org.eclipse.paho.client.mqttv3.MqttConnectOptions;
import org.eclipse.paho.client.mqttv3.MqttDeliveryToken;
import org.eclipse.paho.client.mqttv3.MqttException;
import org.eclipse.paho.client.mqttv3.MqttMessage;
import org.eclipse.paho.client.mqttv3.MqttTopic;
import org.eclipse.paho.client.mqttv3.internal.MemoryPersistence;

public class Service {
 MqttClient client;
 MemoryPersistence persistence = new MemoryPersistence();

 public Service()throws Exception{}

  public static void main(String[] args) throws Exception {
    new Service().doDemo();

  public void doDemo() {
    try {

        client = new MqttClient("tcp://", "testingMyMQTT", persistence);

        MqttConnectOptions opts = new MqttConnectOptions();    


        MainActivity.setT("1");//sets the txt1 in main view to 1 so i know whats going on

        MqttMessage msg = new MqttMessage("Works".getBytes());
        MainActivity.setT("its working");
        MqttTopic topic = client.getTopic("Android/Test");

        MqttDeliveryToken token = topic.publish(msg);

    } catch (MqttException e) {



  1. Verify that android can connect to your local network and if so, check the logs of the Apollo broker.