For what purpose Context class is used in android?Please explain me in depth and be more specific .I read all other posts but none of them were specific enough to give me clear understanding.
I know Content class 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.
Like Here,
Intent intent=new Intent(this,new_class.class);
why we are passing Main activity context into the Intent constructor call.what type of information does this activity context contain,how will it help it ,what type of resource access is it providing to it ?(with example please).
Similarly,
here,
TextView textview=new TextView(this);
Why TextView need activity context?How does it help it.
It act as a Interface to global information about an application environment. This is 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.
You can get all the information from delveloper's official documentation... https://developer.android.com/reference/android/content/Context.html
There are already several good explanations of
Context
on Stackoverflow (see the linked questions and us the "search" feature. Also, the source code for Android is available ongrepcode.com
and you can look yourself if you are really interested. Why trust someone else's answer if you can look yourself? ;-)However, I will answer your specific questions:
In this case (the 2-argument constructor for
Intent
), theContext
parameter is only used to determine the package name of the targetActivity
. Assuming that the package name of your application is "com.example.app", andMyActivity
is an `Activity of your application, the following code snippets are all functionally identical:All
View
s need aContext
. Think of theContext
as the "owner of the View". This controls the lifetime of theView
. In general, aView
should have the same lifetime as its owningActivity
, which is why you usually pass theActivity
as theContext
parameter when creating aView
. When theActivity
is destroyed, all of the ownedView
s are also destroyed. Additionally, theView
uses theContext
to gain access to resources (drawables, layouts, strings, themes, etc.).