In Android, Context is an important component that provides access to application-specific resources and information. It acts as a bridge between the Android system and application components. Context is used to access resources, start activities and services, and interact with different parts of an Android application.
- Provides access to resources such as strings, layouts, databases, and shared preferences.
- Helps interact with Android components like Activities, Services, and Broadcast Receivers.
- Gives information about the application environment and the current state of the app.
The code has been given in both Java and Kotlin Programming Language for Android.
Understanding Context by a Real World Example
Imagine a person staying in a hotel. To get breakfast, lunch, room service, or other facilities, the person contacts the room-service staff.
- Person -> Activity
- Hotel -> Application
- Room-Service Staff -> Context
- Hotel Services -> Resources and Services
Just as room service provides access to hotel facilities, Context provides access to app resources, databases, SharedPreferences, and system services.
How Does this Work?
- Represents the current state of the application: It identifies the active screen or component, such as an inquiry, add, delete, or display screen.
- Provides information about the activity and application: Context helps determine which activity is currently running and what operations can be performed.
- Gives access to application resources and services: It allows access to resources, databases, SharedPreferences, system services, and APIs.
- Extended by both Activity and Application classes: Since Activity and Application inherit from Context, they can access app resources and services. Proper usage is important to avoid memory leaks.
Types of Context in Android
There are mainly two types of Context that are available in Android.
- Application Context and
- Activity Context
The Overall view of the App hierarchy looks like the following:

It can be seen in the above image that in "Sample Application", the nearest Context is Application Context. In "Activity1" and "Activity2", both Activity Context (Here it is Activity1 Context for Activity1 and Activity2 Context for Activity2) and Application Context.The nearest Context to both is their Activity Context only.
Application Context
This Context is tied to the Lifecycle of an Application. Mainly it is an instance that is a singleton and can be accessed via getApplicationContext(). Some use cases of Application Context are:
- If it is necessary to create a singleton object
- During the necessity of a library in an activity
getApplicationContext(): getApplicationContext() returns the Context of the entire application. It is used for application-wide operations such as accessing resources, starting services, and sharing data across multiple activities. Unlike Activity Context, it remains available throughout the application's lifecycle.
Example:
import android.app.Application;
public class GlobalExampleClass extends Application {
private String globalName;
private String globalEmail;
public String getName() {
return globalName;
}
public void setName(String aName) {
globalName = aName;
}
public String getEmail() {
return globalEmail;
}
public void setEmail(String aEmail) {
globalEmail = aEmail;
}
}
import android.app.Application
class GlobalExampleClass : Application() {
private var globalName: String? = null
private var globalEmail: String? = null
fun getName(): String? {
return globalName
}
fun setName(aName: String?) {
globalName = aName
}
fun getEmail(): String? {
return globalEmail
}
fun setEmail(aEmail: String?) {
globalEmail = aEmail
}
}
Inside the activity class, set the name and email of GlobalExampleClass, which can be accessed from another activity. Let us see via the below steps.
Syntax:
// Activity 1
public class <your activity1> extends Activity {
........
........
private <yourapplicationname> globarVar;
........
@Override
public void onCreate(Bundle savedInstanceState) {
.......
final GlobalExampleClass globalExampleVariable = (GlobalExampleClass) getApplicationContext();
// In this activity set name and email and can reuse in other activities
globalExampleVariable.setName("getApplicationContext example");
globalExampleVariable.setEmail("xxxxxx@gmail.com");
.......
}
// Activity 2
public class <your activity2> extends Activity {
........
........
private <yourapplicationname> globarVar;
.......
@Override
public void onCreate(Bundle savedInstanceState) {
.......
final GlobalExampleClass globalExampleVariable = (GlobalExampleClass) getApplicationContext();
// As in activity1, name and email is set, we can retrieve it here
final String globalName = globalExampleVariable.getName();
final String globalEmail = globalExampleVariable.getEmail();
.......
}So, whenever the variable scope is required throughout the application, we can get it by means of getApplicationContext(). Following is a list of functionalities of Application Context.
List of functionalities of Application Context:
- Load Resource Values
- Start a Service
- Bind to a Service
- Send a Broadcast
- Register BroadcastReceiver
Activity Context
It is the activity Context meaning each and every screen got an activity. For example, EnquiryActivity refers to EnquiryActivity only and AddActivity refers to AddActivity only. It is tied to the life cycle of activity. It is used for the current Context. The method of invoking the Activity Context is getContext().
Some use cases of Activity Context are:
- The user is creating an object whose lifecycle is attached to an activity.
- Whenever inside an activity for UI related kind of operations like toast, dialogue, etc.,
getContext(): It returns the Context which is linked to the Activity from which it is called. This is useful when we want to call the Context from only the current running activity.
Example:
@Override
public void onItemClick(AdapterView<?> parent, View view, int pos, long id) {
// view.getContext() refers to the current activity view
// Here it is used to start the activity
Intent intent = new Intent(view.getContext(), <your java classname>::class.java);
intent.putExtra(pid, ID);
view.getContext().startActivity(intent);
}
fun onItemClick(parent: AdapterView<*>?, view: View, pos: Int, id: Long) {
// view.getContext() refers to the current activity view
// Here it is used to start the activity
val intent = Intent(view.context, <your java classname>::class.java)
intent.putExtra(pid, ID)
view.context.startActivity(intent)
}
List of Functionalities of Activity Context:
- Load Resource Values
- Layout Inflation
- Start an Activity
- Show a Dialog
- Start a Service
- Bind to a Service
- Send a Broadcast
- Register BroadcastReceiver
From the functionalities of both Application and Activity, we can see that the difference is that the Application Context is not related to UI. It should be used only to start a service or load resource values etc. Apart from getApplicationContext() and getContext(), getBaseContext() or this are the different terminologies used throughout the app development. Let us see with an example
getBaseContext():
The base Context is set by the constructor or setBaseContext().This method is only valid if we have a ContextWrapper. Android provides a ContextWrapper class that is created around an existing Context using:
ContextWrapper wrapper = new ContextWrapper(context);The benefit of using a ContextWrapper is that it lets you “modify behavior without changing the original Context”.
Syntax:
public <YourHandler>(Context ctx) {
// if the context is instanceof ContextWrapper
while (ctx instanceof ContextWrapper) {
// use getBaseContext()
final Context baseContext = ((ContextWrapper)context).getBaseContext();
if (baseContext == null) {
break;
}
// And then we can assign to context and reuse that
ctx = baseContext;
}
}this:
"this" argument is of a type "Context". To explain this Context let's take an example to show a Toast Message using "this".
Example:
import android.os.Bundle;
import android.widget.Toast;
import androidx.appcompat.app.AppCompatActivity;
// Show a simple toast message, that can be done after doing some activities
// Toast.makeText(this, "Action got completed", Toast.LENGTH_SHORT).show();
public class ExampleActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main_example);
// Displaying Toast
Toast.makeText(this,"Action done",Toast.LENGTH_SHORT).show();
}
}
import android.os.Bundle
import android.widget.Toast
import androidx.appcompat.app.AppCompatActivity
// Show a simple toast message, that can be done after doing some activities
// Toast.makeText(this, "Action got completed", Toast.LENGTH_SHORT).show();
class ExampleActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main_example)
// Displaying Toast
Toast.makeText(this, "Action done", Toast.LENGTH_SHORT).show()
}
}
Another example to start the activity using "this":
import androidx.appcompat.app.AppCompatActivity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.EditText;
public class FirstActivity extends AppCompatActivity {
public static final String newMessage = "Your message to go for next screen";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_first);
}
// There must be some button and on click of
// that below method can be invoked
public void sendMessageToNextScreen(View view) {
// Here it is used with "this"
Intent intent = new Intent(this, SecondActivity.class);
EditText editText = (EditText) findViewById(R.id.editText);
String message = editText.getText().toString();
intent.putExtra(newMessage, message);
// Start the SecondActivity
startActivity(intent);
}
}
import android.content.Intent
import android.os.Bundle
import android.view.View
import android.widget.EditText
import androidx.appcompat.app.AppCompatActivity
class FirstActivity : AppCompatActivity() {
private var newMessage = "Your message to go for next screen"
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_first)
}
// There must be some button and on click of
// that below method can be invoked
fun sendMessageToNextScreen(view: View?) {
// Here it is used with "this"
val intent = Intent(this, SecondActivity::class.java)
val editText: EditText = findViewById(R.id.editText)
val message = editText.text.toString()
intent.putExtra(newMessage, message)
// Start the SecondActivity
startActivity(intent)
}
}