I think this stuff would deserve an Android Dev blog enttry. While I understand what you are saying, remembering it in 6 months time is a different story. If there were a blog post to refer back to, it would be a lot easier.
On Jun 4, 2:29 am, Dianne Hackborn <[email protected]> wrote: > This is my preferred approach for implementing a singleton that needs a > Context: > > static final Object sLock = new Object(); > static MySingleton sInstance; > > static MySingleton getInstance(Application app) { > synchronized (sLock) { > if (sInstance == null) { > sInstance = new MySingleton(app); > } > return sInstance; > } > } > > The locking is very explicit and controlled. I think that using double null > checks for this kind of stuff is very premature optimization, you'd be > better off calling the method once when you need the instance and keeping > the pointer around. > > The method takes an Application object instead of a Context to prevent > mistakes where the developer hands in a transient Context such as for an > Activity. Another way to deal with that though is to explicitly retrieve > the application context from any given context: > > static final Object sLock = new Object(); > static MySingleton sInstance; > > static MySingleton getInstance(Context context) { > synchronized (sLock) { > if (sInstance == null) { > sInstance = new MySingleton( > context.getApplicationContext()); > } > return sInstance; > } > } > > > > > > On Fri, Jun 3, 2011 at 10:14 AM, Chris <[email protected]> wrote: > > Not really, but to the thread in general. > > > Since this has gotten off topic of Android development, I'd like to try to > > pull it back... > > > Mark if you're still paying attention, how would this come up within the > > context of .. a Context? I'm having trouble seeing a useful example. > > > -- > > You received this message because you are subscribed to the Google > > Groups "Android Developers" group. > > To post to this group, send email to [email protected] > > To unsubscribe from this group, send email to > > [email protected] > > For more options, visit this group at > >http://groups.google.com/group/android-developers?hl=en > > -- > Dianne Hackborn > Android framework engineer > [email protected] > > Note: please don't send private questions to me, as I don't have time to > provide private support, and so won't reply to such e-mails. All such > questions should be posted on public forums, where I and others can see and > answer them.- Hide quoted text - > > - Show quoted text - -- You received this message because you are subscribed to the Google Groups "Android Developers" group. To post to this group, send email to [email protected] To unsubscribe from this group, send email to [email protected] For more options, visit this group at http://groups.google.com/group/android-developers?hl=en

