More than You Want to Know about Context
Posted June 26, 2013 at 10:00 pm by Mike Szczys
Context—there’s always a context. It doesn’t take long to get the hang of dealing with the context objects called for in most of the UI portions of your code. But do you really know what these parameters are doing? It’s easy enough to use getApplicationContext(), getActivityContext(), or even just the keyword ‘this‘. But do you know which one to choose?
Dave Smith has already done a good job of describing layout inflation. Now he’s tackled the sticky wicket that is understanding context. This starts with a description of what has a context; obviously this includes Applications, Activities, and Services. But you also need to consider how a Broadcast Receiver and Content Provider interact with context. Specifically, when might you back yourself into an error caused by a context no longer existing? A reference to a null contest will throw an exception (and probably crash your app which users aren’t fond of). The quick and easy answer is to always use the Application context. Dave’s original article outlines the few exceptions to this rule, and presents a couple of interested examples of less than optimal context objects being passed to him.
Want something on the XDA Portal? Send us a tip!