Monday, December 19, 2011

Re: [android-developers] Re: One process, two live Application objects?

Hm, so when do you need to just have code start running in your process first thing?  Generally it needs to run for something else -- and that something else needs to make a call somewhere to get what it wants.  Having that call Singleton.getInstance(context) (at which point you can do init for the first call) isn't any harder that ((Singleton)context.getApplication()), and it has some significant benefits:

When some activity makes a first call to Singleton.getInstance(context), the singleton presumably will keep a reference to the context, directly or transitively; otherwise there would be no need to pass the context.  The result is a memory leak - the singleton will keep a reference to the activity after the activity is destroyed.  Worse, other activities will keep calling singleton's methods that is bound to the invalid context.

IMHO, Application.onCreate() would be the best place to initialize singletons that require a context.  The application context is valid during the lifetime of the application, and its usage does not introduce memory leaks.  Subclassing an application, making it a singleton, and creating getters for other "singleton" objects seems an even better approach.

--
You received this message because you are subscribed to the Google
Groups "Android Developers" group.
To post to this group, send email to android-developers@googlegroups.com
To unsubscribe from this group, send email to
android-developers+unsubscribe@googlegroups.com
For more options, visit this group at
http://groups.google.com/group/android-developers?hl=en

No comments:

Post a Comment