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://10.1.10.1:1883", "testingMyMQTT", persistence);
        MainActivity.setT("2");

        MqttConnectOptions opts = new MqttConnectOptions();    

        opts.setUserName("nabi");
        opts.setPassword("M4rk3".toCharArray());    
        opts.setKeepAliveInterval(480);   

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

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

        MqttDeliveryToken token = topic.publish(msg);

    } catch (MqttException e) {
      e.printStackTrace();
    }
  }

}

1个回答

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