1

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

@Override
public void onCreate(Bundle savedInstanceState){

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

The service initiates the MQTT connection via an AsyncTask.

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

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

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:

@Override
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 https://developer.android.com/training/sync-adapters/creating-sync-adapter.html however this seems more a "connect-once" rather than a continued and established connection.

Any ideas?

Vadim Kotov
  • 8,084
  • 8
  • 48
  • 62
Clocker
  • 1,316
  • 2
  • 19
  • 29

1 Answers1

0

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

https://eclipse.org/paho/clients/android/

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?

Community
  • 1
  • 1
hardillb
  • 54,545
  • 11
  • 67
  • 105
  • Do you have a working example for the Paho Android? there are other questions about this, some say the service continues running even after owning activity is killed - some say the service continues to run. – Clocker Jul 25 '15 at 22:59