In Android programming, what exactly is a Context class and what is it used for?
I read about it on the developer site, but I am unable to understand it clearly.
In Android programming, what exactly is a Context class and what is it used for?
I read about it on the developer site, but I am unable to understand it clearly.
The Context is an abstract class provided by Android, and as such, its job is to bridge your application code with the Android System. Through classes that inherit from Context (activities, services, and your application), your app gains the ability to access resources and functionalities reachable only by the Operating System.
When context descendant objects get instantiated by the Operating System (through an OS controlled instantiation mechanism, like "intents"), they become administered by the Operating System, and as such, they obtain lifecycle.
For anything else, passing a context as a parameter in method calls, allows this method to use the context as a channel of communication with the OS, in order to reach the OS and ask it to perform some action or return some resource.
Visualising the Context together with the Manifest
To visualize the Android Context and Manifest in action, an old calling centre switchboard is a great analogy.
The base is the Android System, where all the wires connecting all the application components of every running app, emerge.
Each "switchboard application" contains some plugholes, which represent the app's manifest component declarations. So through manifest declarations, the Android System learns about the existence of these plugholes so it can plug a new context wire by creating objects through intents.
Each wire represents an Android Context connected to some launchable component of the app, or to the app itself. You can use an existing wire since it is connected with the Android System, in order to request all kinds of things that need to go through the Operating System, to be accomplished.
You can assume that when an activity is destroyed, its wire gets unplugged. While when another activity (or another component) is constructed, a new wire emerges and connects to the correct manifest-declared plughole.
I have written an entire article that explains how the Context couples your app to the android system:
Let's have a small analogy before diving deep in the technicality of Context
Every Boss has an assistant or someone( errand boy) who does less important and more time-consuming things for him. For example, if they need a file or coffee then an assistant will be on run. Boss will not know what is going on in the background but the file or the task will be delivered
So Here
Boss - Android Application
Assistant - Context
File or cup of coffee - Resource
Context is your access point for application-related resources
Let's see some of such resources or tasks
Launching an activity.
Getting an absolute path to the application-specific cache directory on the filesystem.
Determining whether the given permission is allowed for a particular process and user ID running in the system.
Checking whether you have been granted a particular permission.
And so on.
So if an Android application wants to start an activity, it goes straight to Context (Access Point), and the Context class gives him back the resources(Intent in this case).
Like any other class Context class has fields and methods.
You can explore more about Context in official documentation, it covers pretty much everything, available methods, fields, and even how to use fields with methods.
Context means Android get to know in which activity I should go for or act in.
1 - Toast.makeText(context, "Enter All Details", Toast.LENGTH_SHORT).show();
it used in this.
Context context = ActivityName.this;
2 -startActivity(new Intent(context,LoginActivity.class));
in this context means from which activity you wanna go to other activity. context or ActivityName.this is faster then , getContext and getApplicatinContext.
Context means component (or application) in various time-period. If I do eat so much food between 1 to 2 pm then my context of that time is used to access all methods (or resources) that I use during that time. Content is a component (application) for a particular time. The Context of components of the application keeps changing based on the underlying lifecycle of the components or application.
For instance, inside the onCreate() of an Activity,
getBaseContext() -- gives the context of the Activity that is set (created) by the constructor of activity.
getApplicationContext() -- gives the Context setup (created) during the creation of application.
Note: <application> holds all Android Components.
<application>
<activity> .. </activity>
<service> .. </service>
<receiver> .. </receiver>
<provider> .. </provider>
</application>
It means, when you call getApplicationContext() from inside whatever component, you are calling the common context of the whole application.
Context keeps being modified by the system based on the lifecycle of components.
What's Context exactly?
Per the Android reference documentation, it's an entity that represents various environment data. It provides access to local files, databases, class loaders associated to the environment, services (including system-level services), and more. Throughout this book, and in your day-to-day coding with Android, you'll see the Context passed around frequently.
From the "Android in Practice" book, p. 60.
Several Android APIs require a Context as parameter
If you look through the various Android APIs, you’ll
notice that many of them take an android.content.Context object as a
parameter. You’ll also see that an Activity or a Service is usually used as a
Context. This works because both of these classes extend from Context.
for more details about context, read this article. I will explain that briefly.
If you wanna know what is context you must know what it does...
for example getContext() is one of the methods that retrieve context. In getContext(), Context is tied to an Activity and its lifecycle. We can imagine Context as layer which stands behind Activity and it will live as long as Activity lives. The moment the Activity dies, Context will too. this method gives list of functionalities to activity, like:
Load Resource Values,
Layout Inflation,
Start an Activity,
Show a Dialog,
Start a Service,
Bind to a Service,
Send a Broadcast,
Register BroadcastReceiver.
now imagine that :
Context is a layer(interface) which stands behind its component (Activity, Application…) and component’s lifecycle, which provides access to various functionalities which are supported by application environment and Android framework.
Think of Context as a box with different resources: string, colors, and fonts. If you need a resource, you turn to this box. When you rotate the screen, this box changes because the orientation changes to landscape.
If you look at the comment of https://stackoverflow.com/a/16301475/1772898 , you will find a comment by ulf-edholm
Hmmm, to me it all sounds like what we old timers used to call global variables, which was much frowned on when object orientation entered the scene
He is right. Context is an alternative to global variable.
For simplicity we can say that: global variable ≈ context
The benefit of context over global variable is, global variables make it impossible to create two independent instances of the same system in the same process, whereas, The context allows multiple instances of the system to coexist in a single process, each with its own context.
Please check A Philosophy of Software Design by John Ousterhout, 7.5 Pass-through variables.
global variables make it impossible to create two independent instances of the same system in the same process, since accesses to the global variables will conflict.
...
The solution I use most often is to introduce a context object as in Figure 7.2(d). A context stores all of the application’s global state (anything that would otherwise be a pass-through variable or global variable). Most applications have multiple variables in their global state, representing things such as configuration options, shared subsystems, and performance counters. There is one context object per instance of the system. The context allows multiple instances of the system to coexist in a single process, each with its own context.
later in the comment section, you will find another comment by bjornw
If you just grep a codebase you'll see hundreds of different getContext, getBaseContext, getBlaBlaContext.
He is also right.
To reduce the number of methods that must be aware of the context, a reference to the context is referred in many major objects. That is why you see getContext, getBaseContext, getBlaBlaContext .. in so many places.
Reference: A Philosophy of Software Design by John Ousterhout, 7.5 Pass-through variables.
Unfortunately, the context will probably be needed in many places, so it can potentially become a pass-through variable. To reduce the number of methods that must be aware of it, a reference to the context can be saved in most of the system’s major objects. In the example of Figure 7.2(d), the class containing m3 stores a reference to the context as an instance variable in its objects. When a new object is created, the creating method retrieves the context reference from its object and passes it to the constructor for the new object. With this approach, the context is available everywhere, but it only appears as an explicit argument in constructors.