Related
I'm learning Kotlin and I've already had to fill the context several times in different ways, like this, context.application, requireContext() etc.
I'm wondering if there is any way I can realize which context to use by myself instead copying them with tutorials.
There are mainly two type of context in android & both of them are provided to you as a ContextWrapper class object.
Application Context
This context is basically provided/used when you need to do some work that doesn't involves any view/UI operation (where you don't need to refer to/rely on any UI code).
This is mostly helpful when you're doing operations directly via your process that doesn't need any UI interactions like for an example, getting list of contacts via content provider.
So, you can consider this as parent of all other context you can have in your application and apparently this is consistent for your given process.
This context is retrieved via Application class of your app, or via any other activity by requesting like (activity.applicationContext).
Activity Context
This context is basically bounded/limited to given activity you're in right now. This is helpful to mainly do UI operations because, your context is part of the same UI you are in right now.
So, yes you can consider this a child context that can changes as per your activity changes. For most of the cases, it is not preferred to store & share this context across UI/Activities as it can lead to memory leaks.
This context can be retrieved once you're on any activity class via (Activity.this, this, context in fragments & custom views)
I agree personally that context has been confusing topic on Android since the beginning, but if you know C/C++ then I can relate this to 'pointers' (conceptually). Context are pointers for given activity/application class.
There has been a lot of posting about what these two contexts are.. But I'm still not getting it quite right
As I understand it so far:
Each is an instance of its class which means that some programmers recommend you to use this.getApplicationContext() as often as possible in order to not "leak" out any memory. This is because the other this (getting the Activity instance context) points to an Activity that is being destroyed each time the user tilts the phone or leave the app etc.. Which apparently the Garbage Collector (GC) doesn't catch and therefore uses too much memory..
But can anyone please come up with some really good coding examples where it would be the right thing to use this (getting the context of the current Activity instance) and the application context will be useless/wrong?
getApplicationContext() is almost always wrong. Ms. Hackborn (among others) have been very explicit that you only use getApplicationContext() when you know why you are using getApplicationContext() and only when you need to use getApplicationContext().
To be blunt, "some programmers" use getApplicationContext() (or getBaseContext(), to a lesser extent) because their Java experience is limited. They implement an inner class (e.g., an OnClickListener for a Button in an Activity) and need a Context. Rather than using MyActivity.this to get at the outer class' this, they use getApplicationContext() or getBaseContext() to get a Context object.
You only use getApplicationContext() when you know you need a Context for something that may live longer than any other likely Context you have at your disposal. Scenarios include:
Use getApplicationContext() if you need something tied to a Context that itself will have global scope. I use getApplicationContext(), for example, in WakefulIntentService, for the static WakeLock to be used for the service. Since that WakeLock is static, and I need a Context to get at PowerManager to create it, it is safest to use getApplicationContext().
Use getApplicationContext() when you bind to a Service from an Activity, if you wish to pass the ServiceConnection (i.e., the handle to the binding) between Activity instances via onRetainNonConfigurationInstance(). Android internally tracks bindings via these ServiceConnections and holds references to the Contexts that create the bindings. If you bind from the Activity, then the new Activity instance will have a reference to the ServiceConnection which has an implicit reference to the old Activity, and the old Activity cannot be garbage collected.
Some developers use custom subclasses of Application for their own global data, which they retrieve via getApplicationContext(). That's certainly possible. I prefer static data members, if for no other reason than you can only have one custom Application object. I built one app using a custom Application object and found it to be painful. Ms. Hackborn also agrees with this position.
Here are reasons why not to use getApplicationContext() wherever you go:
It's not a complete Context, supporting everything that Activity does. Various things you will try to do with this Context will fail, mostly related to the GUI.
It can create memory leaks, if the Context from getApplicationContext() holds onto something created by your calls on it that you don't clean up. With an Activity, if it holds onto something, once the Activity gets garbage collected, everything else flushes out too. The Application object remains for the lifetime of your process.
I think there's a lot of stuff that is poorly documented on the SDK site, this is one of them. The claim I'm going to make is that it seems as though it's better to default to using an application context and only use an activity context when you really need to. The only place where I've ever seen that you need an activity context is for a progress dialog. SBERG412 claims that you have to use an activity context for a toast message, yet the Android docs clearly show an application context being used. I've always used application context for toasts because of this Google example. If it's wrong to do so, then Google dropped the ball here.
Here's more to think about and review:
For a toast message, the Google Dev Guide uses the application context and explicitly say's to use it:
Toast Notifications
In the dialogs section of the Dev guide, you see that an AlertDialog.Builder uses the application context, and then the progress bar uses an activity context. This isn't explained by Google.
Dialogs
It seems like a good reason to use application context is when you want to handle configuration changes like an orientation change, and you want to retain objects which need a context like Views. If you look here: Run Time Changes
There is a caution about using an activity context, which can create a leak. This can be avoided with an application context with the views that are to be retained (at least that's my understanding). In an app I'm writing, I intend to use an application context because I'm trying to hold over some views and other things on an orientation change, and I still want the activity to be destroy and recreated on orientation changes. Thus I have to use an app context to not cause a memory leak (see Avoiding memory Leaks). To me it seems there are plenty of good reasons to use the application context instead of an activity context, and to me it almost seems like you would use it more often than an activity context. That's what many Android books I've gone through seem to do, and that's what much of the Google examples I've seen do.
The Google documentation really makes it seem like using application context is perfectly fine in most cases, and in fact appears more often than using an activity context in their examples (at least the examples I've seen). If it's really such a problem to use application context, then Google really needs to place more emphasis on this. They need to make it clear, and they need to redo some of their examples. I wouldn't blame this entirely on inexperienced developers since the authority (Google) really makes it look like it's not a problem to use application contexts.
I used this table as a guidance for when to use the different types of Context such as Application context (i.e: getApplicationContext()) and activity context , also BroadcastReceiver context:
All merits go to original author here for more info.
Which context to use?
There are two types of Context:
Application context is associated with the application and will always be same throughout the life of application -- it does not change. So if you are using Toast, you can use application context or even activity context (both) because toast can be displayed from anywhere with in your application and is not attached to a specific window. But there are many exceptions, one exception is when you need to use or pass the activity context.
Activity context is associated with to the activity and can be destroyed if the activity is destroyed -- there may be multiple activities (more than likely) with a single application. And sometimes you absolutely need the activity context handle. For example, should you launch a new activity, you need to use activity context in its Intent so that the new launching activity is connected to the current activity in terms of activity stack. However, you may use application's context too to launch a new activity but then you need to set flag Intent.FLAG_ACTIVITY_NEW_TASK in intent to treat it as a new task.
Let's consider some cases:
MainActivity.this refers to the MainActivity context which extends Activity class but the base class (activity) also extends Context class, so it can be used to offer activity context.
getBaseContext() offers activity context.
getApplication() offers application context.
getApplicationContext() also offers application context.
For more information please check this link.
I was wondering why not to use Application Context for every operation which it supports. In the end it lowers chance of memory leak and missing null check for getContext() or getActivity() (when using injected application context or acquired through static method from Application). Statements, like the one by Ms. Hackborn to use Application Context only if needed, don't seem convincing for me without an explanation why. But it seems that I have found an unswear why:
have found that there are issues on some Android version / device combinations that do not follow these rules. For instance, if I have a BroadcastReceiver that is passed a Context and I convert that Context to an Application Context and then try to call registerReceiver() on the Application Context there are many instances where this works fine, but also many instances where I get a crash because of a ReceiverCallNotAllowedException. These crashes occur on a wide range of Android versions from API 15 up to 22.
https://possiblemobile.com/2013/06/context/#comment-2443283153
Because it's not guaranteed that all operations described as supported by Application Context in the table below will work on all Android devices!
Two great examples of when you should use Activity context vs. the Application context are when displaying either a Toast message or a built-in Dialog message as using the Application context will cause an exception:
ProgressDialog.show(this, ....);
or
Toast t = Toast.makeText(this,....);
Both of these need information from the Activity context that is not provided in the Application context.
Application context live untill your application is alive only and it is not depend on Activity Life Cycle but, context keep object long-lived. If the object which you are used temporary, that time use Application Context and Activity Context is used totally oposite of Application Context.
I just wanted to know how many ways to get the context, which method used in which situation.
Which one better to use, and what is the main and key deference between them.
For Your better understands you should read android official blog. an also look at HackBod Answer.
There are some references URL which help you more about the context
What exactly does using the Application Context mean?
Difference between Activity Context and Application Context
http://android-developers.blogspot.de/2009/01/avoiding-memory-leaks.html
Thanks
Context class represents the local environment of an App, It encapsulates all the services and resources available to the app. There is a base class ApplicationContext, and sub classes for components: Activity, Service etc.
Always prefer using ApplicationContext because it is global and doesn't cause serious issues if its leaked, that is: an unused reference of it stays and is not garbage collected.
Sometimes you have to use sub components like Activity or Service as context. Use this when creating Intents, or creating UI Elements, or showing a toast etc. That is: functions that are specifically bound to these component's identity, its UI or its display window.
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.
Putting it simply:
As the name suggests, it's the context of the current state of the application/object. It lets newly-created objects understand what has been going on. Typically you call it to get information regarding another part of your program (activity and package/application).
You can get the context by invoking getApplicationContext(), getContext(), getBaseContext() or this (when in a class that extends from Context, such as the Application, Activity, Service and IntentService classes).
Typical uses of context:
Creating new objects:
Creating new views, adapters, listeners:
TextView tv = new TextView(getContext());
ListAdapter adapter = new SimpleCursorAdapter(getApplicationContext(), ...);
Accessing standard common resources:
Services like LAYOUT_INFLATER_SERVICE, SharedPreferences:
context.getSystemService(LAYOUT_INFLATER_SERVICE)
getApplicationContext().getSharedPreferences(*name*, *mode*);
Accessing components implicitly:
Regarding content providers, broadcasts, intent
getApplicationContext().getContentResolver().query(uri, ...);
Definition of Context
Context represents environment data
It provides access to things such as databases
Simpler terms (example 1)
Consider Person-X is the CEO of a start-up software company.
There is a lead architect present in the company, this lead architect
does all the work in the company which involves such as database, UI
etc.
Now the CEO Hires a new Developer.
It is the Architect who tells the responsibility of the newly hired
person based on the skills of the new person that whether he will
work on Database or UI etc.
Simpler terms (example 2)
It's like access to android activity to the app's resource.
It's similar to when you visit a hotel, you want breakfast, lunch &
dinner in the suitable timings, right?
There are many other things you like during the time of stay. How do you get these things?
You ask the room-service person to bring these things for you.
Here the room-service person is the context considering you are the
single activity and the hotel to be your app, finally the breakfast, lunch &
dinner has to be the resources.
Things that involve context are:
Loading a resource.
Launching a new activity.
Creating views.
obtaining system service.
Context is the base class for Activity, Service, Application, etc
Another way to describe this: Consider context as remote of a TV & channel's in the television are resources, services, using intents, etc - - - Here remote acts as an access to get access to all the different resources into the foreground.
So, Remote has access to channels such as resources, services, using intents, etc ....
Likewise ... Whoever has access to remote naturally has access to all the things such as resources, services, using intents, etc
Different methods by which you can get context
getApplicationContext()
getContext()
getBaseContext()
or this (when in the activity class)
Example:
TextView tv = new TextView(this);
The keyword this refers to the context of the current activity.
A Context is a handle to the system; it provides services like resolving resources, obtaining access to databases and preferences, and so on. An Android app has activities. Context is like a handle to the environment your application is currently running in. The activity object inherits the Context object.
For more information, look in Introduction to Android development with Android Studio - Tutorial.
Context is an "interface" to the global information about an application environment. In practice, Context is actually an abstract class, whose implementation is provided by the Android system.
It 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.
In the following picture, you can see a hierarchy of classes, where Context is the root class of this hierarchy. In particular, it's worth emphasizing that Activity is a descendant of Context.
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.
Simple Example to understand context in android :
Every boss has an assistant to look after, to do all less important and time-consuming tasks. If a file or a cup of coffee is needed, an assistant is on the run. Some bosses barely know what’s going on in the office, so they ask their assistants regarding this too. They do some work themselves but for most other things they need the help of their assistants.
In this scenario,
Boss – is the Android application
Assistant – is a context
Files/Cup of coffee – are resources
We generally call context when we need to get information about different parts of our application like Activities, Applications, etc.
Some operations(things where the assistant is needed) where context is involved:
Loading common resources
Creating dynamic views
Displaying Toast messages
Launching Activities etc.
Different ways of getting context:
getContext()
getBaseContext()
getApplicationContext()
this
An Android Context is an Interface (in the general sense, not in the Java sense; in Java, Context is actually an abstract class!) that allows access to application specific resources and class and information about application environment.
If your android app was a web app, your context would be something similar to ServletContext (I am not making an exact comparison here).
Your activities and services also extend Context, so they inherit all those methods to access the environment information in which the app is running.
Context represents a handle to get environment data .
Context class itself is declared as abstract, whose implementation is provided by the android OS.
Context is like remote of a TV & channel's in the television are resources, services, etc.
What can you do with it ?
Loading resource.
Launching a new activity.
Creating views.
Obtaining system service.
Ways to get context :
getApplicationContext()
getContext()
getBaseContext()
Just putting it out there for newbies;
So First understand Word Context :
In english-lib. it means:
"The circumstances that form the setting for an event, statement, or
idea, and in terms of which it can be fully understood and assessed."
"The parts of something written or spoken that immediately precede and
follow a word or passage and clarify its meaning."
Now take the same understanding to programming world:
context of current state of the application/object. It lets newly created objects understand what has been going on. Typically you call it to get information regarding another part of your program (activity, package/application)
You can get the context by invoking getApplicationContext(), getContext(), getBaseContext() or this (when in the activity class).
To Get Context Anywhere in application use following code:
Create new class AppContext inside your android application
public class AppContext extends Application {
private static Context context;
public void onCreate(){
super.onCreate();
AppContext.context = getApplicationContext();
}
public static Context getAppContext() {
return AppContext.context;
}
}
Now any time you want application context in non-activity class, call this method and you have application context.
Hope this help ;)
Context is a reference to the current object as this. Also context allows access to information about the application environment.
Think of it as the VM that has siloed the process the app or service is running in. The siloed environment has access to a bunch of underlying system information and certain permitted resources. You need that context to get at those services.
The class android.content.Context provides the connection to the Android system and the resources of the project. It is the interface to global information about the application environment.
The Context also provides access to Android Services, e.g. the Location Service.
Activities and Services extend the Context class.
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:
Context is an interface to global information about an application environment. It's an abstract class whose implementation is provided by the Android system.
Context allows access to application-specific resources and classes, as well as calls for application-level operations such as launching activities, broadcasting and receiving intents, etc.
Here is Example
public class MyActivity extends Activity {
public void Testing() {
Context actContext = this; /*returns the Activity Context since Activity extends Context.*/
Context appContext = getApplicationContext(); /*returns the context of the single, global Application object of the current process. */
Button BtnShowAct1 = (Button) findViewById(R.id.btnGoToAct1);
Context BtnContext = BtnShowAct1.getContext(); /*returns the context of the View. */
For more details you can visit http://developer.android.com/reference/android/content/Context.html
Context is Instances of the the class android.content.Context provide the connection to the Android system which executes the application. For example, you can check the size of the current device display via the Context.
It also gives access to the resources of the project. It is the interface to global information about the application environment.
The Context class also provides access to Android services, e.g., the alarm manager to trigger time based events.
Activities and services extend the Context class. Therefore they can be directly used to access the Context.
Context is context of current state of the application/object.Its an entity that represents various environment data . Context helps the current activity to interact with out side android environment like local files, databases, class loaders associated to the environment, services including system-level services, and more.
A Context is a handle to the system . It provides services like resolving resources, obtaining access to databases and preferences, and so on. An android app has activities. It’s like a handle to the environment your application is currently running in. The activity object inherits the Context object.
Different invoking methods by which you can get context
1. getApplicationContext(),
2. getContext(),
3. getBaseContext()
4. or this (when in the activity class).
Context is basically for resource access and getting the environment details of the application(for application context) or activity (for activity context) or any other...
In order to avoid memory leak you should use application context for every components that needs a context object.... for more click here
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.
Boss Assistant Analogy
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
What official Android Developer site says about Context
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.
A Context is what most of us would call Application. It's made by the Android system and is able to do only what an application is able to.
In Tomcat, a Context is also what I would call an application.
There is one Context that holds many Activities, each Activity may have many Views.
Obviously, some will say that it doesn't fit because of this or that and they are probably right, but saying that a Context is your current application will help you to understand what you are putting in method parameters.
Putting simple, Androids Context is a mess that you won't love until you stop worrying about.
Android Contexts are:
God-objects.
Thing that you want to pass around all your application when you are starting developing for Android, but will avoid doing it when you get a little bit closer to programming, testing and Android itself.
Unclear dependency.
Common source of memory leaks.
PITA for testing.
Actual context used by Android system to dispatch permissions, resources, preferences, services, broadcasts, styles, showing dialogs and inflating layout. And you need different Context instances for some separate things (obviously, you can't show a dialog from an application or service context; layouts inflated from application and activity contexts may differ).
The Context is the android specific api to each app-s Sandbox
that provides access app private data like to resources, database, private filedirectories, preferences, settings ...
Most of the privatedata are the same for all activities/services/broadcastlisteners of one application.
Since Application, Activity, Service implement the Context interface they can be used where an api call needs a Context parameter
Instances of the the class android.content.Context provide the connection to the Android system which executes the application. For example, you can check the size of the current device display via the Context.
It also gives access to the resources of the project. It is the interface to global information about the application environment.
The Context class also provides access to Android services, e.g., the alarm manager to trigger time based events.
Activities and services extend the Context class. Therefore they can be directly used to access the Context.
If you want to connect Context with other familiar classes in Android, keep in mind this structure:
Context < ContextWrapper < Application
Context < ContextWrapper < ContextThemeWrapper < Activity
Context < ContextWrapper < ContextThemeWrapper < Activity <
ListActivity
Context < ContextWrapper < Service
Context < ContextWrapper < Service < IntentService
So, all of those classes are contexts in their own way. You can cast Service and ListActivity to Context if you wish. But if you look closely, some of the classes inherit theme as well. In activity or fragment, you would like theming to be applied to your views, but don't care about it Service class, for instance.
I explain the difference in contexts here.
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.
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.
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.
Context means current.
Context use to do operation for current screen.
ex.
1. getApplicationContext()
2. getContext()
Toast.makeText(getApplicationContext(), "hello", Toast.LENGTH_SHORT).show();
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.
Putting it simply:
As the name suggests, it's the context of the current state of the application/object. It lets newly-created objects understand what has been going on. Typically you call it to get information regarding another part of your program (activity and package/application).
You can get the context by invoking getApplicationContext(), getContext(), getBaseContext() or this (when in a class that extends from Context, such as the Application, Activity, Service and IntentService classes).
Typical uses of context:
Creating new objects:
Creating new views, adapters, listeners:
TextView tv = new TextView(getContext());
ListAdapter adapter = new SimpleCursorAdapter(getApplicationContext(), ...);
Accessing standard common resources:
Services like LAYOUT_INFLATER_SERVICE, SharedPreferences:
context.getSystemService(LAYOUT_INFLATER_SERVICE)
getApplicationContext().getSharedPreferences(*name*, *mode*);
Accessing components implicitly:
Regarding content providers, broadcasts, intent
getApplicationContext().getContentResolver().query(uri, ...);
Definition of Context
Context represents environment data
It provides access to things such as databases
Simpler terms (example 1)
Consider Person-X is the CEO of a start-up software company.
There is a lead architect present in the company, this lead architect
does all the work in the company which involves such as database, UI
etc.
Now the CEO Hires a new Developer.
It is the Architect who tells the responsibility of the newly hired
person based on the skills of the new person that whether he will
work on Database or UI etc.
Simpler terms (example 2)
It's like access to android activity to the app's resource.
It's similar to when you visit a hotel, you want breakfast, lunch &
dinner in the suitable timings, right?
There are many other things you like during the time of stay. How do you get these things?
You ask the room-service person to bring these things for you.
Here the room-service person is the context considering you are the
single activity and the hotel to be your app, finally the breakfast, lunch &
dinner has to be the resources.
Things that involve context are:
Loading a resource.
Launching a new activity.
Creating views.
obtaining system service.
Context is the base class for Activity, Service, Application, etc
Another way to describe this: Consider context as remote of a TV & channel's in the television are resources, services, using intents, etc - - - Here remote acts as an access to get access to all the different resources into the foreground.
So, Remote has access to channels such as resources, services, using intents, etc ....
Likewise ... Whoever has access to remote naturally has access to all the things such as resources, services, using intents, etc
Different methods by which you can get context
getApplicationContext()
getContext()
getBaseContext()
or this (when in the activity class)
Example:
TextView tv = new TextView(this);
The keyword this refers to the context of the current activity.
A Context is a handle to the system; it provides services like resolving resources, obtaining access to databases and preferences, and so on. An Android app has activities. Context is like a handle to the environment your application is currently running in. The activity object inherits the Context object.
For more information, look in Introduction to Android development with Android Studio - Tutorial.
Context is an "interface" to the global information about an application environment. In practice, Context is actually an abstract class, whose implementation is provided by the Android system.
It 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.
In the following picture, you can see a hierarchy of classes, where Context is the root class of this hierarchy. In particular, it's worth emphasizing that Activity is a descendant of Context.
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.
Simple Example to understand context in android :
Every boss has an assistant to look after, to do all less important and time-consuming tasks. If a file or a cup of coffee is needed, an assistant is on the run. Some bosses barely know what’s going on in the office, so they ask their assistants regarding this too. They do some work themselves but for most other things they need the help of their assistants.
In this scenario,
Boss – is the Android application
Assistant – is a context
Files/Cup of coffee – are resources
We generally call context when we need to get information about different parts of our application like Activities, Applications, etc.
Some operations(things where the assistant is needed) where context is involved:
Loading common resources
Creating dynamic views
Displaying Toast messages
Launching Activities etc.
Different ways of getting context:
getContext()
getBaseContext()
getApplicationContext()
this
An Android Context is an Interface (in the general sense, not in the Java sense; in Java, Context is actually an abstract class!) that allows access to application specific resources and class and information about application environment.
If your android app was a web app, your context would be something similar to ServletContext (I am not making an exact comparison here).
Your activities and services also extend Context, so they inherit all those methods to access the environment information in which the app is running.
Context represents a handle to get environment data .
Context class itself is declared as abstract, whose implementation is provided by the android OS.
Context is like remote of a TV & channel's in the television are resources, services, etc.
What can you do with it ?
Loading resource.
Launching a new activity.
Creating views.
Obtaining system service.
Ways to get context :
getApplicationContext()
getContext()
getBaseContext()
Just putting it out there for newbies;
So First understand Word Context :
In english-lib. it means:
"The circumstances that form the setting for an event, statement, or
idea, and in terms of which it can be fully understood and assessed."
"The parts of something written or spoken that immediately precede and
follow a word or passage and clarify its meaning."
Now take the same understanding to programming world:
context of current state of the application/object. It lets newly created objects understand what has been going on. Typically you call it to get information regarding another part of your program (activity, package/application)
You can get the context by invoking getApplicationContext(), getContext(), getBaseContext() or this (when in the activity class).
To Get Context Anywhere in application use following code:
Create new class AppContext inside your android application
public class AppContext extends Application {
private static Context context;
public void onCreate(){
super.onCreate();
AppContext.context = getApplicationContext();
}
public static Context getAppContext() {
return AppContext.context;
}
}
Now any time you want application context in non-activity class, call this method and you have application context.
Hope this help ;)
Context is a reference to the current object as this. Also context allows access to information about the application environment.
Think of it as the VM that has siloed the process the app or service is running in. The siloed environment has access to a bunch of underlying system information and certain permitted resources. You need that context to get at those services.
The class android.content.Context provides the connection to the Android system and the resources of the project. It is the interface to global information about the application environment.
The Context also provides access to Android Services, e.g. the Location Service.
Activities and Services extend the Context class.
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:
Context is an interface to global information about an application environment. It's an abstract class whose implementation is provided by the Android system.
Context allows access to application-specific resources and classes, as well as calls for application-level operations such as launching activities, broadcasting and receiving intents, etc.
Here is Example
public class MyActivity extends Activity {
public void Testing() {
Context actContext = this; /*returns the Activity Context since Activity extends Context.*/
Context appContext = getApplicationContext(); /*returns the context of the single, global Application object of the current process. */
Button BtnShowAct1 = (Button) findViewById(R.id.btnGoToAct1);
Context BtnContext = BtnShowAct1.getContext(); /*returns the context of the View. */
For more details you can visit http://developer.android.com/reference/android/content/Context.html
Context is Instances of the the class android.content.Context provide the connection to the Android system which executes the application. For example, you can check the size of the current device display via the Context.
It also gives access to the resources of the project. It is the interface to global information about the application environment.
The Context class also provides access to Android services, e.g., the alarm manager to trigger time based events.
Activities and services extend the Context class. Therefore they can be directly used to access the Context.
Context is context of current state of the application/object.Its an entity that represents various environment data . Context helps the current activity to interact with out side android environment like local files, databases, class loaders associated to the environment, services including system-level services, and more.
A Context is a handle to the system . It provides services like resolving resources, obtaining access to databases and preferences, and so on. An android app has activities. It’s like a handle to the environment your application is currently running in. The activity object inherits the Context object.
Different invoking methods by which you can get context
1. getApplicationContext(),
2. getContext(),
3. getBaseContext()
4. or this (when in the activity class).
Context is basically for resource access and getting the environment details of the application(for application context) or activity (for activity context) or any other...
In order to avoid memory leak you should use application context for every components that needs a context object.... for more click here
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.
Boss Assistant Analogy
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
What official Android Developer site says about Context
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.
A Context is what most of us would call Application. It's made by the Android system and is able to do only what an application is able to.
In Tomcat, a Context is also what I would call an application.
There is one Context that holds many Activities, each Activity may have many Views.
Obviously, some will say that it doesn't fit because of this or that and they are probably right, but saying that a Context is your current application will help you to understand what you are putting in method parameters.
Putting simple, Androids Context is a mess that you won't love until you stop worrying about.
Android Contexts are:
God-objects.
Thing that you want to pass around all your application when you are starting developing for Android, but will avoid doing it when you get a little bit closer to programming, testing and Android itself.
Unclear dependency.
Common source of memory leaks.
PITA for testing.
Actual context used by Android system to dispatch permissions, resources, preferences, services, broadcasts, styles, showing dialogs and inflating layout. And you need different Context instances for some separate things (obviously, you can't show a dialog from an application or service context; layouts inflated from application and activity contexts may differ).
The Context is the android specific api to each app-s Sandbox
that provides access app private data like to resources, database, private filedirectories, preferences, settings ...
Most of the privatedata are the same for all activities/services/broadcastlisteners of one application.
Since Application, Activity, Service implement the Context interface they can be used where an api call needs a Context parameter
Instances of the the class android.content.Context provide the connection to the Android system which executes the application. For example, you can check the size of the current device display via the Context.
It also gives access to the resources of the project. It is the interface to global information about the application environment.
The Context class also provides access to Android services, e.g., the alarm manager to trigger time based events.
Activities and services extend the Context class. Therefore they can be directly used to access the Context.
If you want to connect Context with other familiar classes in Android, keep in mind this structure:
Context < ContextWrapper < Application
Context < ContextWrapper < ContextThemeWrapper < Activity
Context < ContextWrapper < ContextThemeWrapper < Activity <
ListActivity
Context < ContextWrapper < Service
Context < ContextWrapper < Service < IntentService
So, all of those classes are contexts in their own way. You can cast Service and ListActivity to Context if you wish. But if you look closely, some of the classes inherit theme as well. In activity or fragment, you would like theming to be applied to your views, but don't care about it Service class, for instance.
I explain the difference in contexts here.
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.
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.
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.
Context means current.
Context use to do operation for current screen.
ex.
1. getApplicationContext()
2. getContext()
Toast.makeText(getApplicationContext(), "hello", Toast.LENGTH_SHORT).show();