【问题标题】:Having trouble connecting android with MQTT to broker将带有 MQTT 的 android 连接到代理时遇到问题
【发布时间】:2014-06-27 14:13:13
【问题描述】:

我正在尝试连接到 Apollo 代理,当我在普通 Java 项目中单独使用它时,此代码运行良好,一切都完全相同,除了现在它在一个 android 项目中,我尝试在单击时运行它MainActivity 中的一个按钮。

在我尝试连接 MQttClient 之前,我有一个更新为“1”的文本框,但是第二个 .setT("2") 没有运行,所以我认为问题出在 client.connect(opts) 上我只是做 client.connect() 文本框被更新为“2”,但由于我需要用户名和密码,所以其余部分无法运行

我刚开始使用 MQTT 学习。感谢您的帮助。

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();
    }
  }

}

【问题讨论】:

    标签: java android messaging mqtt


    【解决方案1】:

    验证 android 是否可以连接到您的本地网络 10.1.10.1,如果可以,请检查 Apollo 代理的日志。

    【讨论】: