1

I am trying to make a simple Hello World style program for the android device and test my MQTT broker running on my localhost. This is what I have done so far:

@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...
}

Everytime I run the code, it runs the else block. I'm not sure what I'm doing wrong, as I have Mosquitto running and the localhost address is what's displayed in my ipconfig, so I don't really know what I'm doing wrong.

All Help Is Appreciated!

HTG
  • 584
  • 1
  • 8
  • 28

1 Answers1

0

Looking at the doc for the MQTTAndroidClient it says it's is an implementation of the IMqttAsyncClient, meaning methods will return immediately and continue in the background,

This means that the client is unlikely to have completed connecting by the time you call mqttClient.connect();

Given you are running this code in on create (where you should not really run blocking tasks) you should look at using the onSuccess callback to detect when the connection has completed e.g.:

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);
  }
});
hardillb
  • 54,545
  • 11
  • 67
  • 105