How to Use Context Correctly in Android

Image for post
Image for post
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:

  • Getting information regarding the activity and application.
  • Getting access to the database, application-specific resources (strings, drawable, …) and classes, filesystems, and shared preferences.
  • Up-calls for application-level operations such as launching activities, broadcasting, and receiving intents.

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:

  • Application Context: This Context is bound to the life cycle of an application. That means as long as the application has not been killed, it is available. Chiefly it is a singleton instance that can be accessed from your application class via getApplicationContext(). The application Context can be used where you need a Context whose lifecycle is separate from the current Context. The main point about application Context is that it is not UI related Context. So, if we want to start an activity by using an intent or showing a toast or anything else related to the UI, even If we are fetching something that should be themed, we shouldn’t use the application Context. Notice that holding a reference to activity in a long-living object or thread can cause a memory leak. In this case, also use the application Context. Below is the list of application Context functionalities:
  • Activity Context: As it is obvious this Context is bound to the life cycle of activity and is accessible as long as activity lives via getContext(). We should use the activity Context when we want to call the Context from only the current running activity and for operations related to the UI such as:

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:

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

Also thisrefers 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:

A self-learner

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