Clocker Clocker - 8 days ago 4
Android Question

Android Long Lasting MQTT connection

I am in need to initiate a connection after an application is closed - onDestroy() is called and the app is no longer visible.

MainActivity initiates a service in the

public void onCreate(Bundle savedInstanceState){

if(savedInstanceState == null) {
startService(new Intent(MainActivity.this, MqttService.class));

The service initiates the MQTT connection via an AsyncTask.

public int onStartCommand(Intent intent, int flags, int startId){

Notification note = createNotification();
//startForeground(20, note);
new MqttTask().execute(CONNECT_RETRIES);

The MQTT connection is kept alive as long as the application is kept alive because the service is also ready. The service also implements some callback methods which I am in need of use, specifically:

public void messageArrived(String s, MqttMessage mqttMessage) throws Exception {

My goal is to allow the connection to be alive even when the application is closed, so that the user can receive messages via the connection without having the app open. I guess the idea is to reconnect when the app is destroyed

What I've tried:

1) I don't like this solution because, though it works, it provides an annoying notification for the user

startForeground(23, createNotification());

2) I've attempted to use an AlarmManager to call startService(MqttService.class) on a certain interval though according to the best practices this is not recommended.

3) I've looked at the however this seems more a "connect-once" rather than a continued and established connection.

Any ideas?


Have you looked at the Paho Android service rather that writing your own?

This should run in the background and remain running until it's explicitly killed.

Also if you want to continue to use your own service then you should look at this previous question.

How to restart a killed service automatically?