0

I am working on an application in which I need a connection to a server. I also need to access this connection from different activities.
To achieve this I was going to override the Application class and create the connection there. This would allow for easy interaction from every Activity as I could simply call getApplicationContext().getConnection() to get access to my own connection class.

The problem with this approach is that the Application class does not have any onDestroy() method or similar in which I can release the connection and any related resources. I do not think that leaving it idle until onLowMemory() is called is the best approach here.
I cannot add a custom release() method, as I don't know when to call it (there are two Activities that can be the last one to be active, and depending on the users actions they do not know if the other is to be started when the active one is shut down).

Is there a good solution to this, should I just ignore releasing resources (before onLowMemory()) or is there a better way to achieve what I want (possibly a Service, but as there will be several calls to an underlying class it might get overly problematic with the Service?)

Jave
  • 31,598
  • 14
  • 77
  • 90

1 Answers1

0

Just use Singleton Design Pattern. Making your Connection class Singleton gives you approach to access connection from different activities, and don`t forget to handle multithreading.

Dmytro Danylyk
  • 19,684
  • 11
  • 62
  • 68
  • I was hoping to avoid using a singleton, for two reasons; first I think that the code would be cleaner and make more sense with the connection in the application context, and secondly because I would still have the problem with releasing the resources in a singleton, but the singleton wouldn't even have the `onLowMemory()` method. Multithreading is already cared for :) – Jave Mar 01 '12 at 15:27
  • "there are two Activities that can be the last one to be active, and depending on the users actions they do not know if the other is to be started when the active one is shut down" - you can add static counter to count Activities, and if there is only 1 opened activity call release(). – Dmytro Danylyk Mar 01 '12 at 16:04
  • Yes, that is what I had in mind too, it could be done with both the Application or the singleton way. I was considering something like a reference counter in the application and when there are no longer any active references, it starts a timer, and if there are still no active references after the time is up, release the resources. This question has some good discussion on singletons vs. application: http://stackoverflow.com/questions/3826905/singletons-vs-application-context-in-android – Jave Mar 02 '12 at 09:02
  • Why don't you extend Activity class instead of Application? You will not have problems with the Context, as it actually extends it. – Caumons Mar 11 '12 at 13:28