I am using Eclipse Paho android mqtt service in my app. I am able to subscribe and publish the messages to mqtt broker. I have couple of Activities in the app, when any acti
A 'better' way would be to create a Service
which connects/reconnects to the MQTT Broker.
I created my own service called MqttConnectionManagerService
which maintains and manages connection to the broker.
Key features of this solution:
START_STICKY
)startService(..)
again would trigger its onStartCommand()
method (and not onCreate()
). In this method, we simply check if this client is connected to the broker and connect/reconnect if required.Sample code:
MqttConnectionManagerService
public class MqttConnectionManagerService extends Service {
private MqttAndroidClient client;
private MqttConnectOptions options;
@Override
public void onCreate() {
super.onCreate();
options = createMqttConnectOptions();
client = createMqttAndroidClient();
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
this.connect(client, options);
return START_STICKY;
}
private MqttConnectOptions createMqttConnectOptions() {
//create and return options
}
private MqttAndroidClient createMqttAndroidClient() {
//create and return client
}
public void connect(final MqttAndroidClient client, MqttConnectOptions options) {
try {
if (!client.isConnected()) {
IMqttToken token = client.connect(options);
//on successful connection, publish or subscribe as usual
token.setActionCallback(new IMqttActionListener() {..});
client.setCallback(new MqttCallback() {..});
}
} catch (MqttException e) {
//handle e
}
}
}
AndroidManifest.xml
MqttServiceStartReceiver
public class MqttServiceStartReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
context.startService(new Intent(context, MqttConnectionManagerService.class));
}
}
In your Activity's
onResume()
startService(new Intent(this, MqttConnectionManagerService.class));