Keeping a service running during orientation changes

Option 1: if you want the service to be destroyed, immediately when the main activity is finishing, but not during rotation:

To avoid automatic service stop you must start it manually before binding:

protected void onStart() {
  Intent intent = new Intent(getApplicationContext(), MServcie.class);
  startService(intent);
  bindService(intent, connection, Context.BIND_AUTO_CREATE);
}

Stop the service only if your Activity is finishing!

protected void onStop() {
  if (service != null) {
    unbindService(connection);
    service = null;
    if (isFinishing()) {
      stopService(new Intent(getApplicationContext(), MyServcie.class));
    }
  }
}

Option 2: if you want the os to decide when the service is being stopped.

protected void onStart() {
    Intent intent = new Intent(this, MServcie.class);
    getApplicationContext().bindService(intent, this, Context.BIND_AUTO_CREATE);
}

One approach you could use, is check to see if the Activity isFinishing() before unbinding in your onPause(). If it is finishing, you would defer the unbinding to your onDestroy() method. Before onDestroy() is called, however, you could persist your ServiceConnection in the onRetainNonConfigurationInstance() method. If you do perform that persistence, than you wouldn't actually call unBind() inside of on your onDestroy() at all and simply let the new instance of your Activity do the unbinding.

That being said, depending on your application, you might find it is just easier to start/stop your service.


As you probably know already, a Service is really for having a separate lifecycle from Activities. As such, you could consider not using a Service for the purely monitoring scenario. You only need a lifecycle separate from Activities in the background case, but not in the purely monitoring case.

What you really seem to want is for your logging to be tied to the lifetime of your Application and for you to be able to control the lifetime of your Application through either starting/stopping Activities or your Service. If you did your polling in a separate thread accessible from the Application object, your Activities won't need to bind with a Service at all, but simply communicate with this logging thread. When you do want the background logging, you could start/stop the service which would also communicate with the logging thread to gracefully cleanup on stop, restart correctly, etc.

Tags:

Android