androidresource-managementunmanagedresources

Is there some standard way to explicitly close services and other resources?


For instance when using database connection, threading or IO streams (all what is required explicit closing/free up) is there some standard way of doing this? Perhaps by implementing some standard interface so Framework/class consumer would be able call this resources cleanup logic for my class?

For those who have some experiance with .NET Framework analogue would be IDisposable interface, so by implementing this interface I can put all resource-cleanup logic in Dispose() method so class consumers would be able check whether an instance of a class implements IDisposable interface and then call Dispose() explicitly.

Is there something built in Android as well?


Solution

  • Yes, Services and Activities have lifecycles. When they are 'closed', the onDestroy() method will be called. There are multiple lifecycle methods in Android and it is really important to learn when to use what. This is described on the following pages: http://developer.android.com/reference/android/app/Activity.html http://developer.android.com/reference/android/app/Service.html

    From these onDestroy() methods, you should close your resources. If you have a lot of resources to close, you might want to let them implement an interface and store these resources into a collection so that you can loop through your resources when onDestroy is called.