I'm trying to write an application in android to publish mqtt messages. I'm using an AsyncTask to publish to my broker but sometimes I have a big delay I guess is because I have to connect to the broker every time before publishing
@Override
protected Void doInBackground(String... params) {
try {
settings = new AppSettings(context);
if (!settings.getBroker().isEmpty()) {
client = new MqttClient(settings.getBroker(), MQTTService.ANDROID_ID, new MemoryPersistence());
if (!settings.getUsername().isEmpty() || settings.getPassword().isEmpty()) {
MqttConnectOptions options = new MqttConnectOptions();
options.setUserName(settings.getUsername());
options.setPassword(settings.getPassword().toCharArray());
client.setCallback(new MQTTPushCallback(context));
client.connect(options);
} else {
client.setCallback(new MQTTPushCallback(context));
client.connect();
}
if (client.isConnected()) {
client.publish(settings.getTopic(), new MqttMessage(params[0].getBytes()));
} else {
Log.d(TAG, "Client is not connected to the mqtt service");
}
} else {
Log.d(TAG, "Broker URL unavailable !");
}
} catch (MqttException e) {
e.printStackTrace();
}
return null;
}
My question is , is there a better way of doing this , maybe keeping the connection alive maybe in a service ?
Best regards,
Paul.