How to Use Context Correctly in Android

Photo by Denny Müller on Unsplash

The Context in Android is one of the most important objects and actually is the Context of the current state of the application with major responsibilities such as:

As you can see, almost everything in Android needs access to Context, so if we use it wrong, it can lead to memory leaks. Mainly there are two types of Context:

1. Load resource values,
2. Start a service,
3. Bind to a service,
4. Send a broadcast,
5. Register broadcastReceiver.

1. Load resource values,
2. Layout inflation,
3. Start an activity,
4. Show a dialog or a toast
5. Start a service,
6. Bind to a service,
7. Send a broadcast,
8. Register broadcastReceiver.

Other than above mentioned getApplicationContext() and getContext(), you might have seen getBaseContext() and this as the Context in Android. getBaseContext() is the method of ContextWrapper which is:

Proxying implementation of Context that simply delegates all of its calls to another Context. Can be subclassed to modify behavior without changing the original Context.

With getBaseContext() we can fetch the existing Context inside the ContextWrapper class.

Also this refers to the instance of the class and can be used whenever the Context is needed inside an activity. Below are a few use cases that require a Context object using Java and Kotlin:



Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store