What is Context in Android?

Android apps are popular for a long time and it is evolving to a greater level as user’s expectations are that they need to view the data that they want in an easier smoother view. Hence, the android developers must know the important terminologies before developing the app. In Android Programming we generally come across a word context. So what exactly is this context and why is it so important? To answer this question lets first see what the literal meaning of context is:  

The circumstances that form the setting for an event, statement, or idea, and in terms of which it can be fully understood

Looking at this definition we come across two things: 

  • The context tells us about the surrounding information.
  • It is very important to understand the environment which we want to understand.

Similarly when we talk about the Android Programming context can be understood as something which gives us the context of the current state of our application. We can break the context and its use into three major points: 

  • It allows us to access resources.
  • It allows us to interact with other Android components by sending messages.
  • It gives you information about your app environment.

In the official Android documentation, context is defined as:  

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.



Understanding Context by a Real World Example

Let’s a person visit a hotel. He needs breakfast, lunch, and dinner at a suitable time. Except for these things there are also many other things, he wants to do during the time of stay. So how does he get these things? He will ask the room-service person to bring these things for him. Right? So 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 have to be the resources.

How Does This Work?

1. It is the context of the current/active state of the application.

Usually, the app got multiple screens like display/inquiry/add/delete screens(General requirement of a basic app). So when the user is searching for something, the context is an inquiry screen in this case.

2. It is used to get information about the activity and application.

The inquiry screen’s context specifies that the user is in inquiry activity, and he/she can submit queries related to the app

3. It is used to get access to resources, databases, and shared preferences, etc.

Via Rest services, API calls can be consumed in android apps. Rest Services usually hold database data and provide the output in JSON format to the android app. The context for the respective screen helps to get hold of database data and the shared data across screens

4. Both the Activity and Application classes extend the Context class.



In android, context is the main important concept and the wrong usage of it leads to memory leakage. Activity refers to an individual screen and Application refers to the whole app and both extend the context class. 

Types of Context in Android

There are mainly two types of context are available in Android. 

  1. Application Context and 
  2. Activity Context

The Overall view of the App hierarchy looks like the following:

app hierarchy

It can be seen in the above image that in “Sample Application”, 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 life cycle 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():

It is used to return the context which is linked to the Application which holds all activities running inside it. When we call a method or a constructor, we often have to pass a context and often we use “this” to pass the activity context or “getApplicationContext” to pass the application context. This method is generally used for the application level and can be used to refer to all the activities. For example, if we want to access a variable throughout the android app, one has to use it via getApplicationContext().

Example:

Java

filter_none

edit
close

play_arrow

link
brightness_4
code

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;
  }
}

chevron_right


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.



Java

filter_none

edit
close

play_arrow

link
brightness_4
code

// 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();
      
    .......
}

chevron_right


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:

Java

filter_none

edit
close

play_arrow

link
brightness_4
code

@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);
  intent.putExtra(pid, ID);
  view.getContext().startActivity(intent);
}

chevron_right


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 no way 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” 

Example:

Java

filter_none

edit
close

play_arrow

link
brightness_4
code

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;
  }
  .....
}

chevron_right


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:

Java

filter_none

edit
close

play_arrow

link
brightness_4
code

// Show a simple toast message, that can be done after doing some activities
// Toast.makeText(this, "Action got completed", Toast.LENGTH_SHORT).show();
import android.support.v7.app.AppCompatActivity;  
import android.os.Bundle;  
import android.widget.Toast;    
public class ExampleActivity extends AppCompatActivity {  
    
    @Override  
    protected void onCreate(Bundle savedInstanceState) {  
        super.onCreate(savedInstanceState);  
        setContentView(R.layout.activity_main_example);   
        
        // Displaying Toast with Hello Javatpoint message  
        Toast.makeText(this,"Action done",Toast.LENGTH_SHORT).show();  
    }  
}

chevron_right


Output:

output

Another example to start the activity using “this”:

Java

filter_none

edit
close

play_arrow

link
brightness_4
code

public class FirstActivity extends AppCompatActivity {
    public static final String New_Message = "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(New_Message, message);
        // Start the SecondActivity
        startActivity(intent); 
    }
}

chevron_right


Document References:

Attention reader! Don’t stop learning now. Get hold of all the important Java and Collections concepts with the Fundamentals of Java and Java Collections Course at a student-friendly price and become industry ready.




My Personal Notes arrow_drop_up

Freelancer in Software projects using Java, Python, SQL,MongoDB technologies Can able to quickly adapt to any new technologies and can provide guidance in software projects

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.


Article Tags :
Practice Tags :


2


Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.