Search code examples
androidandroid-serviceandroid-activityandroid-2.3-gingerbread

How could a service detect that an activity has closed?


I have a service both of started and bound type (as defined here). It is started to run indefinitely, then a separate application binds to it: when this application is destroyed, it calls the unbindService on its onDestroy method.

The service should detect that this application is finished. I read about onUnbind method, which is called when all clients have disconnected from a particular interface published by the service. However I need to know not when all clients are disconnected, but any disconnection. Is it possible?

I thought that, during the closing (inside the onDestroy method) the application could send a message to the service (taking advantage of the fact that the service is bound): later it should invoke the unbindService method, as follows.

// method of the application
@Override
public void onDestroy() {
    super.onDestroy();
    service.closed();   // service is defined by IService.aidl
    unbindService(...);
}

In this way the application would send the last message to the service (service.closed() method) and then unbind the service. Could it work correctly? Does the service.closed() method return when the message arrived at its destination? Or could there be a risk that the message is not delivered due to the next call to unbindService method?


Solution

  • Is it possible?

    Have the activity call a method on the Binder before unbinding to indicate that it is dropping the connection.

    Could it work correctly?

    It should. AIDL calls are synchronous, so unbindService() will not occur until after the Binder has been called with closed(), in your sample.