我正在尝试为Android设备创建一个简单的Hello World样式程序,并测试在我的localhost上运行的MQTT代理。这是我到目前为止所做的:
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
String broker = "tcp://192.168.X.X:1883";
String clientID = "AndroidClient";
final MqttAndroidClient mqttClient = new MqttAndroidClient(MainActivity.this, broker, clientID);
try {
mqttClient.connect();
} catch (MqttException e) {
e.printStackTrace();
Toast.makeText(MainActivity.this, "Something Went Wrong", Toast.LENGTH_SHORT).show();
}
if(mqttClient.isConnected()){
Toast.makeText(MainActivity.this, "Hello World!", Toast.LENGTH_SHORT).show();
}else{
Toast.makeText(MainActivity.this, "Could not connect to the server!", Toast.LENGTH_SHORT).show();
return;
}
//Do more things...
}
每次运行代码时,都会运行else块。我不确定我做错了什么,因为我有Mosquitto运行,localhost地址是我的ipconfig中显示的内容,所以我真的不知道我做错了什么。
感谢所有帮助!
答案 0 :(得分:0)
查看MQTTAndroidClient的文档,它说它是IMqttAsyncClient的实现,意味着方法将立即返回并在后台继续,
这意味着在您致电mqttClient.connect();
鉴于你在create(你不应该真正运行阻塞任务)中运行这段代码,你应该看看使用onSuccess
回调来检测连接何时完成,例如:
IMqttToken conToken;
conToken = asyncClient.connect("some context",new new MqttAsyncActionListener() {
public void onSuccess(IMqttToken asyncActionToken) {
log("Connected");
}
public void onFailure(IMqttToken asyncActionToken, Throwable exception) {
log ("connect failed" +exception);
}
});