What is context in android ?

 The topic of Context in Android seems to be confusing too many. People just know that Context is needed quite often to do basic things in Android. People sometimes panic because they try to do perform some operation that requires the Context and they don’t know how to “get” the right Context. I’m going to try to demystify the idea of Context in Android. A full treatment of the issue is beyond the scope of this post, but I’ll try to give a general overview so that you have a sense of what Context is and how to use it. 

What exactly is Context?

Well, the documentation itself provides a rather straightforward explanation: The Context class is an “Interface to global information about an application environment".
The Context class itself is declared as abstract class, whose implementation is provided by the Android OS. The documentation further provides that Context “…allows access to application-specific resources and classes, as well as up-calls for application-level operations such as launching activities, broadcasting and receiving intents, etc".
You can understand very well, now, why the name is Context. It’s because it’s just that. The Context provides the link or hook, if you will, for an Activity, Service, or any other component, thereby linking it to the system, enabling access to the global application environment. In other words: the Context provides the answer to the components question of “where the hell am I in relation to app generally and how do I access/communicate with the rest of the app?” If this all seems a bit confusing, a quick look at the methods exposed by the Context class provides some further clues about its true nature.

Here’s a random sampling of those methods: 1. getAssets() 2. getResources() 3. getPackageManager() 4. getString() 5. getSharedPrefsFile()
What do all these methods have in common? They all enable whoever has access to the Context to be able to access application-wide resources.
Context, in other words, hooks the component that has a reference to it to the rest of application environment. The assets (think ’/assets’ folder in your project), for example, are available across the application, provided that an Activity, Service or whatever knows how to access those resources. Same goes for “getResources()” which allows to do things like “getResources().getColor()” which will hook you into the colors.xml resource (nevermind that aapt enables access to resources via java code, that’s a separate issue).
The upshot is that Context is what enables access to system resources and its what hooks components into the “greater app".


Popular Posts