On Sun, Mar 27, 2011 at 11:58 AM, Kostya Vasilyev <[email protected]> wrote: >> Any Singleton, manager, or utility class can take Context as a parameter >> for the functions it needs it for, making it clear to the user of the API >> that a Context is needed for that functionality > > Sure, that's another way. I prefer to not do this, but coding style is a > personal thing.
Singletons, manager, or utility classes should not be caching a Context. At most, they should be caching an Application, to prevent people from accidentally caching short-lived Contexts (e.g., Activity, Service). > However, there are cases where a true global context is required, and > passing a local Context as a parameter causes a leak. Agreed. That is covered by TreKing's "Use it when you need to store a context in an object that lives longer than an instance of an activity or service, but don't want to leak that activity or service". A fine example here is dealing with configuration changes in an activity that needs to bind to a service: http://commonsware.com/blog/2010/09/29/another-use-getapplicationcontext-binding-rotation.html or trying to get to sticky broadcasts from a BroadcastReceiver: http://commonsware.com/blog/2010/09/12/real-use-getapplicationcontext.html I used to use lines like TreKing's "Never use getApplicationContext()", but I've tried to be a tad more nuanced in recent months. That being said, there is no question in my mind that, in a support board like this, getApplicationContext() is a major code smell. Most times, it is not needed, and can sometimes give erroneous results. -- Mark Murphy (a Commons Guy) http://commonsware.com | http://github.com/commonsguy http://commonsware.com/blog | http://twitter.com/commonsguy Android Training in Oslo: http://bit.ly/fjBo24 -- 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

