I'm writing an Android app that has both an Activity and a Service component. Furthermore, I've got a class encapsulating a resource that I am sharing in several places across both the Activity and the Service. My question is how I can figure out when to free the resource. As I understand it, Java does not have a notion of a destructor, so I can't just create a destructor in the shared object which will be called when there are no more references to the object. Android has functions such as onPause for the Activity, and onDestroy for the Service, although technically there is no guarantee that either of these functions will be called under all possible shutdown circumstances (e.g. the low memory killer won't call these functions). And in any case, it is possible for the Activity to be destroyed without the Service being destroyed, in which case there could still be references to the resource, so I can't just blindly free the resource in that case either.
Since Java does not have a destructor, some sources say to create one's own "close()" type function and call it manually. But it seems like for this to work I would have to maintain my own reference counting scheme, and this seems rather strange considering that Java already has GC which should eliminate the need for such a scheme.
What's the proper solution here?